chrome24+, firesfox26+起支持classList2.0,即让它同时添加或删除多个类名, toggle方法支持第2个参数,用于强制添加或删除
var div = document.createElement("div"); div.classList.add("a", "b"); if (div.className !== "a b" && window.DOMTokenList) { var _add = DOMTokenList.prototype.add; DOMTokenList.prototype.add = function() { for (var i in arguments) { _add.call(this, arguments[i]); } }; var _remove = DOMTokenList.prototype.remove; DOMTokenList.prototype.remove = function() { for (var i in arguments) { _remove.call(this, arguments[i]); } }; DOMTokenList.prototype.toggle = function(token, forse) { token += ""; var result = this.contains(token) , method = result ? forse !== true && "remove" : forse !== false && "add"; if (method) { this[method](token); } return !result; }; }
div.className =
"";
div.classList.add(
"aaa"
,
"ccc"
);
alert(div.className);
时间: 2024-10-12 18:01:42