阅读这篇 Mozilla Developer Network:

因为 ClassName属性是字符串类型的,所以可以使用任何 JavaScript 实现中的常规 String 对象函数:

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

  • 如果要删除类,只需使用 String.replace,将“[ className ]”替换为空字符串。最后使用 String.trim删除 element.className开始和结束处的空白字符。

添加 css 类: cssClassesStr += cssClassName;

移除 css 类: cssClassStr = cssClassStr.replace(cssClassName,"");

Add 属性‘ Class’: object.setAttribute("class", ""); //pure addition of this attribute

移除属性: object.removeAttribute("class");

我只是写了这些:

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;
}

我认为它们能在所有浏览器中工作。

解决办法就是

返回文章页面

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

免责声明: 我相信支持 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));


}

修正了来自@Paulpro 的解决方案

  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;
}

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

对于 更老浏览器,你可以改变 element.className:

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


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

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

这里有一个例子:
假设您有一个 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
}

下面是用纯 javascript 解决方案实现 addClass、 RemoveClass、 hasClass 的解决方案。

其实是 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,' ');
}
}

改进版本的埃米尔的代码(带修剪())

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();
}
}

看看这些油嘴滑舌的人:

  1. 删除类别:

    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');
    

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

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(' ');
}

为了以防万一,如果有人想要为元素构建原型函数,下面是我在需要操作不同对象的类时使用的方法:

Element.prototype.addClass = function (classToAdd) {
var classes = this.className.split(' ')
if (classes.indexOf(classToAdd) === -1) classes.push(classToAdd)
this.className = classes.join(' ')
}


Element.prototype.removeClass = function (classToRemove) {
var classes = this.className.split(' ')
var idx =classes.indexOf(classToRemove)
if (idx !== -1) classes.splice(idx,1)
this.className = classes.join(' ')
}

像这样使用它们: document.body.addClass('whatever')document.body.removeClass('whatever')

您也可以使用任何其他元素(div、 span 等等)来代替 body

一个简单易懂的方法:

// Add class
DOMElement.className += " one";
// Example:
// var el = document.body;
// el.className += " two"


// Remove class
function removeDOMClass(element, className) {
var oldClasses      = element.className,
oldClassesArray = oldClasses.split(" "),
newClassesArray = [],
newClasses;


// Sort
var currentClassChecked,
i;
for ( i = 0; i < oldClassesArray.length; i++ ) {
// Specified class will not be added in the new array
currentClassChecked = oldClassesArray[i];
if( currentClassChecked !== className ) {
newClassesArray.push(currentClassChecked);
}
}


// Order
newClasses = newClassesArray.join(" ");


// Apply
element.className = newClasses;


return element;


}
// Example:
// var el = document.body;
// removeDOMClass(el, "two")

Https://gist.github.com/sorcamarian/ff8db48c4dbf4f5000982072611955a2