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


当前回答

对于IE v6-9(其中不支持classList,并且不希望使用polyfills):

var elem = document.getElementById('some-id');

// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';

elem.setAttribute('class', classList);

其他回答

下面是一个简单的jQuery代码:

$(".class1").click(function(argument) {
    $(".parentclass").removeClass("classtoremove");
    setTimeout(function (argument) {
        $(".parentclass").addClass("classtoadd");
    }, 100);
});

在这里

Class1是事件的侦听器。父类是托管要更改的类的类Classtoremove是您的旧类。要添加的类是要添加的新类。100是类被改变的超时延迟。


选项。

这里有一个小样式与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")


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

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

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

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, ' ') + "]");

这对我很有用:

function setCSS(eleID) {
    var currTabElem = document.getElementById(eleID);

    currTabElem.setAttribute("class", "some_class_name");
    currTabElem.setAttribute("className", "some_class_name");
}

可以这样使用node.className:

document.getElementById('foo').className = 'bar';

根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。