Javascript 有没有办法使用 classList 在一条指令中添加/删除多个类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11115998/
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
Is there a way to add/remove several classes in one single instruction with classList?
提问by Enrique Moreno Tent
So far I have to do this:
到目前为止,我必须这样做:
elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");
While this is doable in jQuery, like this
虽然这在 jQuery 中是可行的,但像这样
$(elem).addClass("first second third");
I'd like to know if there's any native way to add or remove.
我想知道是否有任何本地方式来添加或删除。
回答by iwege
elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");
is equal
是平等的
elem.classList.add("first","second","third");
回答by morkro
The new spread operatormakes it even easier to apply multiple CSS classes as array:
新的展开运算符使将多个 CSS 类应用为数组变得更加容易:
const list = ['first', 'second', 'third'];
element.classList.add(...list);
回答by Rich O'Kelly
The classList
property ensures that duplicate classes are not unnecessarily added to the element. In order to keep this functionality, if you dislike the longhand versions or jQuery version, I'd suggest adding an addMany
function and removeMany
to DOMTokenList
(the type of classList
):
该classList
属性可确保不会将重复的类不必要地添加到元素中。为了保留此功能,如果您不喜欢普通版本或 jQuery 版本,我建议添加一个addMany
函数和removeMany
to DOMTokenList
(类型classList
):
DOMTokenList.prototype.addMany = function(classes) {
var array = classes.split(' ');
for (var i = 0, length = array.length; i < length; i++) {
this.add(array[i]);
}
}
DOMTokenList.prototype.removeMany = function(classes) {
var array = classes.split(' ');
for (var i = 0, length = array.length; i < length; i++) {
this.remove(array[i]);
}
}
These would then be useable like so:
然后这些可以像这样使用:
elem.classList.addMany("first second third");
elem.classList.removeMany("first third");
Update
更新
As per your comments, if you wish to only write a custom method for these in the event they are not defined, try the following:
根据您的评论,如果您只想在未定义的情况下为这些编写自定义方法,请尝试以下操作:
DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function(classes) {...}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function(classes) {...}
回答by Andrés Carre?o
Since the add()
method from the classList
just allows to pass separate arguments and not a single array, you need to invoque add()
using apply. For the first argument you will need to pass the classList
reference from the same DOM node and as a second argument the array of classes that you want to add:
由于add()
来自classList
just的方法允许传递单独的参数而不是单个数组,因此您需要add()
使用 apply调用。对于第一个参数,您需要传递classList
来自同一 DOM 节点的引用,并作为第二个参数传递要添加的类数组:
element.classList.add.apply(
element.classList,
['class-0', 'class-1', 'class-2']
);
回答by Andrés Carre?o
To add class to a element
向元素添加类
document.querySelector(elem).className+=' first second third';
UPDATE:
更新:
Remove a class
删除一个类
document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" ");
回答by Andy E
Newer versions of the DOMTokenList specallow for multiple arguments to add()
and remove()
, as well as a second argument to toggle()
to force state.
在较新版本的DOMTokenList规范允许多个参数add()
和remove()
,以及第二个参数给toggle()
到受力状态。
At the time of writing, Chrome supports multiple arguments to add()
and remove()
, but none of the other browsers do. IE 10 and lower, Firefox 23 and lower, Chrome 23 and lower and other browsers do not support the second argument to toggle()
.
在写这篇文章的时候,Chrome支持多参数add()
和remove()
,但没有其他浏览器的事。IE 10 及更低版本、Firefox 23 及更低版本、Chrome 23 及更低版本等浏览器不支持toggle()
.
I wrote the following small polyfill to tide me over until support expands:
我写了以下小 polyfill 来帮助我渡过难关,直到支持扩展:
(function () {
/*global DOMTokenList */
var dummy = document.createElement('div'),
dtp = DOMTokenList.prototype,
toggle = dtp.toggle,
add = dtp.add,
rem = dtp.remove;
dummy.classList.add('class1', 'class2');
// Older versions of the HTMLElement.classList spec didn't allow multiple
// arguments, easy to test for
if (!dummy.classList.contains('class2')) {
dtp.add = function () {
Array.prototype.forEach.call(arguments, add.bind(this));
};
dtp.remove = function () {
Array.prototype.forEach.call(arguments, rem.bind(this));
};
}
// Older versions of the spec didn't have a forcedState argument for
// `toggle` either, test by checking the return value after forcing
if (!dummy.classList.toggle('class1', true)) {
dtp.toggle = function (cls, forcedState) {
if (forcedState === undefined)
return toggle.call(this, cls);
(forcedState ? add : rem).call(this, cls);
return !!forcedState;
};
}
})();
A modern browser with ES5 compliance and DOMTokenList
are expected, but I'm using this polyfill in several specifically targeted environments, so it works great for me, but it might need tweaking for scripts that will run in legacy browser environments such as IE 8 and lower.
一个符合 ES5 标准的现代浏览器,DOMTokenList
是预期的,但我在几个特定目标环境中使用这个 polyfill,所以它对我来说非常有用,但它可能需要调整将在传统浏览器环境(如 IE 8 及更低版本)中运行的脚本.
回答by Pankaj Parkar
You can do like below
你可以像下面这样
Add
添加
elem.classList.add("first", "second", "third");
Remove
消除
elem.classList.remove("first", "second", "third");
TLDR;
TLDR;
In straight forward case above removal should work. But in case of removal, you should make sure class exists before you remove them
在直截了当的情况下,上述移除应该有效。但是在删除的情况下,您应该在删除它们之前确保类存在
const classes = ["first","second","third"];
classes.forEach(c => {
if (elem.classList.contains(c)) {
element.classList.remove(c);
}
})
回答by colecmc
Here is a work around for IE 10 and 11 users that seemed pretty straight forward.
这是 IE 10 和 11 用户的解决方法,看起来非常简单。
var elem = document.getElementById('elem');
['first','second','third'].map(item => elem.classList.add(item));
<div id="elem">Hello World!</div>
Or
或者
var elem = document.getElementById('elem'),
classes = ['first','second','third'];
classes.map(function(item) {
return elem.classList.add(item);
});
<div id="elem">Hello World!</div>
回答by Soren
A very simple, non fancy, but working solution that I would have to believe is very cross browser:
我不得不相信一个非常简单、非花哨但有效的解决方案是非常跨浏览器的:
Create this function
创建这个函数
function removeAddClasses(classList,removeCollection,addCollection){
for (var i=0;i<removeCollection.length;i++){
classList.remove(removeCollection[i]);
}
for (var i=0;i<addCollection.length;i++){
classList.add(addCollection[i]);
}
}
Call it like this: removeAddClasses(node.classList,arrayToRemove,arrayToAdd);
像这样调用它: removeAddClasses(node.classList,arrayToRemove,arrayToAdd);
...where arrayToRemove is an array of class names to remove: ['myClass1','myClass2'] etcetera
...其中 arrayToRemove 是要删除的类名数组:['myClass1','myClass2'] 等等
...and arrayToAdd is an array of class names to add: ['myClass3','myClass4'] etcetera
...和 arrayToAdd 是要添加的类名数组:['myClass3','myClass4'] 等等
回答by HBP
The standard definiton allows only for adding or deleting a single class. A couple of small wrapper functions can do what you ask :
标准定义只允许添加或删除单个类。几个小的包装函数可以满足您的要求:
function addClasses (el, classes) {
classes = Array.prototype.slice.call (arguments, 1);
console.log (classes);
for (var i = classes.length; i--;) {
classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/);
for (var j = classes[i].length; j--;)
el.classList.add (classes[i][j]);
}
}
function removeClasses (el, classes) {
classes = Array.prototype.slice.call (arguments, 1);
for (var i = classes.length; i--;) {
classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/);
for (var j = classes[i].length; j--;)
el.classList.remove (classes[i][j]);
}
}
These wrappers allow you to specify the list of classes as separate arguments, as strings with space or comma separated items, or a combination. For an example see http://jsfiddle.net/jstoolsmith/eCqy7
这些包装器允许您将类列表指定为单独的参数、带有空格或逗号分隔项的字符串或组合。有关示例,请参阅http://jsfiddle.net/jstoolsmith/eCqy7