如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?


当前回答

这里有一个toggleClass来切换/添加/删除元素上的类:

// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
    var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
    var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));

    elem.className=elem.className.replace(matchRegExp, ''); // clear all
    if (add) elem.className += ' ' + theClass;
}

参见JSFiddle。

也可以在这里看到动态创建新类的答案。

其他回答


选项。

这里有一个小样式与classList的示例,让您了解您有哪些可用选项,以及如何使用classList完成您想要的操作。

样式与类别列表

style和classList之间的区别在于,使用style可以将其添加到元素的样式财产中,但classList有点控制元素的类(add、remove、toggle、contain),我将向您展示如何使用add和remove方法,因为它们是最流行的方法。


样式示例

如果要将margin-top属性添加到元素中,可以这样做:

// Get the Element
const el = document.querySelector('#element');

// Add CSS property 
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.

classList示例

假设我们有一个<div class=“class-a class-b”>,在本例中,我们已经向div元素添加了两个类,class-a和class-b,我们希望控制删除哪些类和添加哪些类。这就是classList变得方便的地方。

删除类-b

// Get the Element
const el = document.querySelector('#element');

// Remove class-b style from the element
el.classList.remove("class-b")

添加类-c

// Get the Element
const el = document.querySelector('#element');

// Add class-b style from the element
el.classList.add("class-c")


使用纯JavaScript代码:

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(ele, cls) {
    if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}

function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

function replaceClass(ele, oldClass, newClass){
    if(hasClass(ele, oldClass)){
        removeClass(ele, oldClass);
        addClass(ele, newClass);
    }
    return;
}

function toggleClass(ele, cls1, cls2){
    if(hasClass(ele, cls1)){
        replaceClass(ele, cls1, cls2);
    }else if(hasClass(ele, cls2)){
        replaceClass(ele, cls2, cls1);
    }else{
        addClass(ele, cls1);
    }
}

你也可以这样做:

document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');

要切换类(如果存在则删除,否则添加):

document.getElementById('id').classList.toggle('class');

对之前的正则表达式进行了一些小注释和调整:

如果类列表不止一次包含类名,则需要全局执行该操作。而且,您可能希望从类列表的末尾去掉空格,并将多个空格转换为一个空格,以防止出现空格。如果只有使用类名的代码使用下面的正则表达式并在添加名称之前删除名称,那么这些都不会是问题。好吧,谁知道谁可能在篡改班级名单。

这个正则表达式是不区分大小写的,所以在不考虑类名中的大小写的浏览器上使用代码之前,可能会出现类名中的错误。

var s = "testing   one   four  one  two";
var cls = "one";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");

我会使用jQuery编写如下内容:

jQuery(function($) {
    $("#some-element").click(function() {
        $(this).toggleClass("clicked");
    });
});

这段代码添加了一个函数,当单击id some元素的元素时调用该函数。如果元素的class属性还不是它的一部分,则该函数会将单击的内容追加到该元素的class特性中,如果它存在,则会将其删除。

是的,您确实需要在页面中添加对jQuery库的引用才能使用这段代码,但至少您可以确信库中的大多数函数都可以在几乎所有现代浏览器上运行,并且这将节省您实现自己代码的时间。