html-JavaScript CSS如何向一个元素添加和删除多个CSS类

如何在不使用任何库的情况下通过javascript将多个CSS类分配给html元素?

anonymous asked 2020-01-30T03:06:43Z
13个解决方案
50 votes

试试这个...

document.getElementById("MyElement").className += " MyClass";

在这里得到这个...

Ryan answered 2020-01-30T03:06:58Z
45 votes

这是通过classList.add()(由所有现代浏览器支持,如此处其他答案所述)添加多个类的更简单方法:

classList.add()

从:[https://developer.mozilla.org/zh-CN/docs/Web/API/Element/classList#Examples]

如果您有要添加到元素中的类名称数组,则可以使用ES6传播运算符通过以下单行将它们全部传递给classList.add()

let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);

请注意,并非所有浏览器本身都支持ES6,因此,与其他任何ES6答案一样,您可能想要使用Babel这样的转译器,或者只是坚持使用ES5并使用上述@LayZee之类的解决方案。

ericsoco answered 2020-01-30T03:07:36Z
29 votes

这有效:

myElement.className = 'foo bar baz';
moff answered 2020-01-30T03:07:55Z
12 votes
var el = document.getElementsByClassName('myclass')

el[0].classList.add('newclass');

el[0].classList.remove('newclass');

若要查找该类是否存在,请使用:

el[0].classList.contains('newclass'); // this will return true or false 

浏览器支持IE8 +

Mano bharathi answered 2020-01-30T03:08:20Z
8 votes

保证可以在新的浏览器上使用。 旧的className方法可能不适用,因为它已被弃用。

<element class="oneclass" />

element.setAttribute('class', element.getAttribute('class') + ' another');
alert(element.getAttribute('class')); // oneclass another
Tor Valamo answered 2020-01-30T03:08:40Z
6 votes

由于我无处找不到这个答案:

ES6方式(现代浏览器)

el.classList.add("foo", "bar", "baz");
Lemures answered 2020-01-30T03:09:04Z
2 votes

也许:

document.getElementById("myEle").className = "class1 class2";

未经测试,但应该可以。

tarnfeld answered 2020-01-30T03:09:28Z
2 votes

只是用这个

element.getAttributeNode("class").value += " antherClass";

注意太空,避免将旧班级与新班级混为一谈

Maged Rawash answered 2020-01-30T03:09:52Z
2 votes

您可以使用不同的内置方法以相同的方式添加和删除多个类:

const myElem = document.getElementById('element-id');
//add multiple classes
myElem.classList.add('class-one', 'class-two', 'class-three');
//remove multiple classes
myElem.classList.remove('class-one', 'class-two', 'class-three');
1_bug answered 2020-01-30T03:10:12Z
1 votes

尝试这个:

function addClass(element, value) {
  if(!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}

类似的逻辑可用于制作removeClass函数。

tybro0103 answered 2020-01-30T03:10:36Z
1 votes

在现代浏览器中,支持classList API。

这样就可以使用(原始)JavaScript函数,如下所示:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];

        // Loop through the array of classes to add one class at a time
        for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
            className = classArray[j];

            element.classList.add(className);
        }
    }
};

现代浏览器(非IE)支持将多个参数传递给classList::add函数,这将消除对嵌套循环的需要,从而使函数有些简化:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var classList, className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];
        classList = element.classList;

        // Pass the array of classes as multiple arguments to classList::add
        classList.add.apply(classList, classArray);
    }
};

用法

addClasses('.button', ['large', 'primary']);

功能版本

var addClassesToElement, addClassesToSelection;

addClassesToElement = function (element, classArray) {
    'use strict';

    classArray.forEach(function (className) {
       element.classList.add(className);
    });
};

addClassesToSelection = function (selector, classArray) {
    'use strict';

    // Use Array::forEach on NodeList to iterate over results.
    // Okay, since we’re not trying to modify the NodeList.
    Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
        addClassesToElement(element, classArray)
    });
};

// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])

classList::add函数将阻止同一CSS类的多个实例,而不是前面的某些答案。

关于classList API的资源:

  • 我可以用吗
  • MDN
  • 大卫·沃尔什
  • HTML5 Doctor
Lars Gyrup Brink Nielsen answered 2020-01-30T03:11:40Z
1 votes

至少有几种不同的方式:

var buttonTop = document.getElementById("buttonTop");

buttonTop.className = "myElement myButton myStyle";

buttonTop.className = "myElement";

buttonTop.className += " myButton myStyle";

buttonTop.classList.add("myElement");

buttonTop.classList.add("myButton", "myStyle");

buttonTop.setAttribute("class", "myElement");

buttonTop.setAttribute("class", buttonTop.getAttribute("class") + " myButton myStyle");

buttonTop.classList.remove("myElement", "myButton", "myStyle");
theMaxx answered 2020-01-30T03:12:00Z
0 votes

也许这可以帮助您学习:

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='output'></div>
  </div>
</body>
</html>1984
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='output'></div>
  </div>
</body>
</html>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='output'></div>
  </div>
</body>
</html>

StackSlave answered 2020-01-30T03:14:25Z
translate from https://stackoverflow.com:/questions/1988514/javascript-css-how-to-add-and-remove-multiple-css-classes-to-an-element