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


当前回答

我在代码中使用了以下普通JavaScript函数。它们使用正则表达式和indexOf,但不需要在正则表达式中引用特殊字符。

function addClass(el, cn) {
    var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
        c1 = (" " + cn + " ").replace(/\s+/g, " ");
    if (c0.indexOf(c1) < 0) {
        el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
    }
}

function delClass(el, cn) {
    var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
        c1 = (" " + cn + " ").replace(/\s+/g, " ");
    if (c0.indexOf(c1) >= 0) {
        el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
    }
}

您也可以在现代浏览器中使用element.classList。

其他回答

无意冒犯,但动态更改类是不清楚的,因为它迫使CSS解释器重新计算整个网页的视觉呈现。

原因是CSS解释器几乎不可能知道是否可以更改任何继承或级联,因此简单的答案是:

永远不要动态更改className!-)

但通常只需要更改一两个属性,这很容易实现:

function highlight(elm){
    elm.style.backgroundColor ="#345";
    elm.style.color = "#fff";
}

对于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这样的库,这是最简单的:

<input type="button" onClick="javascript:test_byid();" value="id='second'" />

<script>
function test_byid()
{
    $("#second").toggleClass("highlight");
}
</script>

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

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

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

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

function classed(el, class_name, add_class) {
  const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
  if (add_class && !el.className.match(re)) el.className += " " + class_name
  else if (!add_class) el.className = el.className.replace(re, '');
}

使用PeterBoughton的答案,这里有一个简单的跨浏览器函数来添加和删除类。

添加类:

classed(document.getElementById("denis"), "active", true)

删除类:

classed(document.getElementById("denis"), "active", false)