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


当前回答

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

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

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

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

其他回答

是的,有很多方法可以做到这一点。在ES6语法中,我们可以很容易地实现。使用此代码切换添加和删除类。

const tabs=document.querySelectorAll('.menu-li');for(制表符的let制表符){tab.onclick=函数(){let activetab=document.querySelectorAll('li.active');activetab[0].classList.remove('active')tab.classList.add('active');}}正文{填充:20px;字体系列:无衬线;}上一页{边距:20px 0;列表样式:无;}李{背景:#dfdfdf;填充:10px;边距:6px 0;光标:指针;}li.活动{背景:#2794c7;字号:粗体;颜色:#ffffff;}<i> 请单击项目:</i><ul class=“menu”><li class=“active”><span>三个</span></li><li>两个</span></li><li>一个</span></li></ul>


选项。

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


在支持Internet Explorer 6的普通JavaScript中更改元素的类

您可以尝试使用node attributes属性来保持与旧浏览器(甚至Internet Explorer 6)的兼容性:

函数getClassNode(元素){对于(var i=element.attributes.length;i-;)if(element.attributes[i].nodeName=='class')return元素.attributes[i];}函数removeClass(classNode,className){var索引,classList=classNode.value.split(“”);如果((index=classList.indexOf(className))>-1){classList.拼接(索引,1);classNode.value=classList.join(“”);}}函数hasClass(classNode,className){return classNode.value.indexOf(className)>-1;}函数addClass(classNode,className){if(!hasClass(classNode,className))classNode.value+=“”+className;}document.getElementById('message').addEventListener('click',function(){var classNode=getClassNode(this);var className=hasClass(classNode,“red”)&&“blue”| |“red”;removeClass(classNode,'red');removeClass(classNode,'blue');addClass(classNode,className);}).红色{颜色:红色;}.红色:之前{内容:“我红了!”;}.红色:之后{content:'再次';}.蓝色{颜色:蓝色;}.蓝色:之前{内容:“我是蓝色的!”}<span id=“message”class=“”>单击我</span>

哇,奇怪这里有这么多过分的答案。。。

<div class="firstClass" onclick="this.className='secondClass'">

我在代码中使用了以下普通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。