如何在 JavaScript 中添加/删除类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6787383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:11:08  来源:igfitidea点击:

How to add/remove a class in JavaScript?

javascriptdomcross-browser

提问by Pacerier

Since element.classListis not supported in IE 9 and Safari-5, what's an alternative cross-browser solution?

由于element.classListIE 9 和 Safari-5 不支持,有什么替代的跨浏览器解决方案?

No-frameworksplease.

无框架

Solution mustwork in at least IE 9, Safari 5, FireFox 4, Opera 11.5, and Chrome.

解决方案必须至少适用于IE 9Safari 5、FireFox 4、Opera 11.5 和 Chrome。

Related posts (but does not contain solution):

相关帖子(但不包含解决方案):

  1. how to add and remove css class

  2. Add and remove a class with animation

  3. Add remove class?

  1. 如何添加和删除css类

  2. 添加和删​​除带有动画的类

  3. 添加删除类?

采纳答案by Yago DLT

One way to play around with classes without frameworks/libraries would be using the property Element.className, which "gets and sets the value of the class attribute of the specified element." (from the MDN documentation).
As @matías-fidemraizeralready mentioned in his answer, once you get the string of classes for your element you can use any methods associated with strings to modify it.

在没有框架/库的情况下使用类的一种方法是使用属性 Element.className,它“获取和设置指定元素的类属性的值。”(来自MDN 文档)。
正如@matías-fidemraizer在他的回答中已经提到的那样,一旦您获得元素的类字符串,您就可以使用与字符串关联的任何方法来修改它。

Here's an example:
Assuming you have a div with the ID "myDiv" and that you want to add to it the class "main__section" when the user clicks on it,

下面是一个示例:
假设您有一个 ID 为“myDiv”的 div,并且您想在用户单击它时向其中添加“main__section”类,

window.onload = init;

function init() {
  document.getElementById("myDiv").onclick = addMyClass;
}

function addMyClass() {
  var classString = this.className; // returns the string of all the classes for myDiv
  var newClass = classString.concat(" main__section"); // Adds the class "main__section" to the string (notice the leading space)
  this.className = newClass; // sets className to the new string
}

回答by emil

Here is solution for addClass, removeClass, hasClass in pure javascript solution.

这是纯javascript解决方案中addClass、removeClass、hasClass的解决方案。

Actually it's from http://jaketrent.com/post/addremove-classes-raw-javascript/

实际上它来自http://jaketrent.com/post/addremove-classes-raw-javascript/

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

function addClass(ele,cls) {
  if (!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,' ');
  }
}

回答by Paul

I just wrote these up:

我刚刚写了这些:

function addClass(el, classNameToAdd){
    el.className += ' ' + classNameToAdd;   
}

function removeClass(el, classNameToRemove){
    var elClass = ' ' + el.className + ' ';
    while(elClass.indexOf(' ' + classNameToRemove + ' ') !== -1){
         elClass = elClass.replace(' ' + classNameToRemove + ' ', '');
    }
    el.className = elClass;
}

I think they'll work in all browsers.

我认为它们适用于所有浏览器。

回答by Wernight

The simplest is element.classListwhich has remove(name), add(name), toggle(name), and contains(name)methods and is now supported by all major browsers.

最简单的是element.classList它具有remove(name)add(name)toggle(name)contains(name)方法,现在所有主要浏览器都支持

For olderbrowsers you change element.className. Here are two helper:

对于较旧的浏览器,您可以更改element.className. 这里有两个帮手:

function addClass(element, className){
    element.className += ' ' + className;   
}

function removeClass(element, className) {
    element.className = element.className.replace(
        new RegExp('( |^)' + className + '( |$)', 'g'), ' ').trim();
}

回答by Sergio Belevskij

Look at these oneliners:

看看这些oneliners:

  1. Remove class:

    element.classList.remove('hidden');
    
  2. Toggle class (adds the class if it's not already present and removes it if it is)

    element.classList.toggle('hidden');
    
  1. 删除类:

    element.classList.remove('hidden');
    
  2. 切换类(如果该类不存在则添加该类,如果存在则将其删除)

    element.classList.toggle('hidden');
    

That's all! I made a test - 10000 iterations. 0.8s.

就这样!我做了一个测试 - 10000 次迭代。0.8 秒。

回答by Matías Fidemraizer

Read this Mozilla Developer Network article:

阅读这篇 Mozilla 开发者网络文章:

Since element.classNameproperty is of type string, you can use regular String object functions found in any JavaScript implementation:

由于element.className属性是字符串类型,您可以使用任何 JavaScript 实现中的常规 String 对象函数:

  • If you want to add a class, first use String.indexOfin order to check if class is present in className. If it's not present, just concatenate a blank character and the new class name to this property. If it's present, do nothing.

  • If you want to remove a class, just use String.replace, replacing "[className]" with an empty string. Finally use String.trimto remove blank characters at the start and end of element.className.

  • 如果要添加类,请首先使用String.indexOf以检查className 中是否存在类。如果它不存在,只需将一个空白字符和新的类名连接到此属性。如果它存在,什么都不做。

  • 如果您想删除一个类,只需使用String.replace,用空字符串替换“[className]”。最后用于String.trim删除开头和结尾的空白字符element.className

回答by Drew

Fixed the solution from @Paulpro

修复了@Paulpro 的解决方案

  1. Do not use "class", as it is a reserved word
  2. removeClassfunction was broken, as it bugged out after repeated use.
  1. 不要使用“class”,因为它是一个保留字
  2. removeClass功能被破坏,因为它在重复使用后被窃听。

`

`

function addClass(el, newClassName){
    el.className += ' ' + newClassName;   
}

function removeClass(el, removeClassName){
    var elClass = el.className;
    while(elClass.indexOf(removeClassName) != -1) {
        elClass = elClass.replace(removeClassName, '');
        elClass = elClass.trim();
    }
    el.className = elClass;
}

回答by Raynos

The solution is to

解决办法是

Shim .classList:

垫片.classList

Either use the DOM-shimor use Eli Grey's shim below

要么使用DOM 垫片,要么使用下面的 Eli Grey 垫片

Disclaimer:I believe the support is FF3.6+, Opera10+, FF5, Chrome, IE8+

免责声明:我相信支持 FF3.6+、Opera10+、FF5、Chrome、IE8+

/*
 * classList.js: Cross-browser full element.classList implementation.
 * 2011-06-15
 *
 * By Eli Grey, http://eligrey.com
 * Public Domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

/*global self, document, DOMException */

/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/

if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) {

(function (view) {

"use strict";

var
      classListProp = "classList"
    , protoProp = "prototype"
    , elemCtrProto = (view.HTMLElement || view.Element)[protoProp]
    , objCtr = Object
    , strTrim = String[protoProp].trim || function () {
        return this.replace(/^\s+|\s+$/g, "");
    }
    , arrIndexOf = Array[protoProp].indexOf || function (item) {
        var
              i = 0
            , len = this.length
        ;
        for (; i < len; i++) {
            if (i in this && this[i] === item) {
                return i;
            }
        }
        return -1;
    }
    // Vendors: please allow content code to instantiate DOMExceptions
    , DOMEx = function (type, message) {
        this.name = type;
        this.code = DOMException[type];
        this.message = message;
    }
    , checkTokenAndGetIndex = function (classList, token) {
        if (token === "") {
            throw new DOMEx(
                  "SYNTAX_ERR"
                , "An invalid or illegal string was specified"
            );
        }
        if (/\s/.test(token)) {
            throw new DOMEx(
                  "INVALID_CHARACTER_ERR"
                , "String contains an invalid character"
            );
        }
        return arrIndexOf.call(classList, token);
    }
    , ClassList = function (elem) {
        var
              trimmedClasses = strTrim.call(elem.className)
            , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
            , i = 0
            , len = classes.length
        ;
        for (; i < len; i++) {
            this.push(classes[i]);
        }
        this._updateClassName = function () {
            elem.className = this.toString();
        };
    }
    , classListProto = ClassList[protoProp] = []
    , classListGetter = function () {
        return new ClassList(this);
    }
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error's toString() is sufficient here.
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
    return this[i] || null;
};
classListProto.contains = function (token) {
    token += "";
    return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function (token) {
    token += "";
    if (checkTokenAndGetIndex(this, token) === -1) {
        this.push(token);
        this._updateClassName();
    }
};
classListProto.remove = function (token) {
    token += "";
    var index = checkTokenAndGetIndex(this, token);
    if (index !== -1) {
        this.splice(index, 1);
        this._updateClassName();
    }
};
classListProto.toggle = function (token) {
    token += "";
    if (checkTokenAndGetIndex(this, token) === -1) {
        this.add(token);
    } else {
        this.remove(token);
    }
};
classListProto.toString = function () {
    return this.join(" ");
};

if (objCtr.defineProperty) {
    var classListPropDesc = {
          get: classListGetter
        , enumerable: true
        , configurable: true
    };
    try {
        objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
    } catch (ex) { // IE 8 doesn't support enumerable:true
        if (ex.number === -0x7FF5EC54) {
            classListPropDesc.enumerable = false;
            objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
        }
    }
} else if (objCtr[protoProp].__defineGetter__) {
    elemCtrProto.__defineGetter__(classListProp, classListGetter);
}

}(self));

}

回答by vagovszkym

Improved version of emil's code (with trim())

emil 代码的改进版本(使用trim())

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

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

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

回答by scott_trinh

function addClass(element, classString) {
    element.className = element
        .className
        .split(' ')
        .filter(function (name) { return name !== classString; })
        .concat(classString)
        .join(' ');
}

function removeClass(element, classString) {
    element.className = element
        .className
        .split(' ')
        .filter(function (name) { return name !== classString; })
        .join(' ');
}