如何在不使用任何库的情况下通过javascript将多个css类分配给html元素?
试试这个:
function addClass(element, value) {
if(!element.className) {
element.className = value;
} else {
newClassName = element.className;
newClassName+= " ";
newClassName+= value;
element.className = newClassName;
}
}
可以使用类似的逻辑来创建removeClass函数。
在现代浏览器中,classList API是supported。
这允许像这样的(vanilla)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上的资源:
至少有几种不同的方式:
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");
也许这会帮助你学习:
//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
addClassName = function(element, className){
var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');
if(!element.className.match(rx)){
element.className += ' '+className;
}
return element.className;
}
removeClassName = function(element, className){
element.className = element.className.replace(new RegExp('\s?'+className), '');
return element.className;
}
var out = E('output'), mn = doc.getElementsByClassName('main')[0];
out.innerHTML = addClassName(mn, 'wow');
out.innerHTML = addClassName(mn, 'cool');
out.innerHTML = addClassName(mn, 'it works');
out.innerHTML = removeClassName(mn, 'wow');
out.innerHTML = removeClassName(mn, 'main');
}); // close load
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!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>
这是一个更简单的方法,通过classList
添加多个类(由所有现代浏览器支持,如此处的其他答案中所述):
div.classList.add('foo', 'bar'); // add multiple classes
来自:https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples
如果你有一个要添加到元素的类名数组,你可以使用ES6 spread operator通过这个单行将它们全部传递到classList.add()
:
let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);
请注意,并非所有浏览器本身都支持ES6,因此与任何其他ES6答案一样,您可能希望使用像Babel这样的转换器,或者只是坚持使用ES5并使用类似@ LayZee的解决方案。
这有效:
myElement.className = 'foo bar baz';
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 +
保证在新的浏览器上工作。旧的className方式可能不会,因为它已被弃用。
<element class="oneclass" />
element.setAttribute('class', element.getAttribute('class') + ' another');
alert(element.getAttribute('class')); // oneclass another
因为我无法找到这个答案:
ES6方式(现代浏览器)
el.classList.add("foo", "bar", "baz");
也许:
document.getElementById("myEle").className = "class1 class2";
没有测试,但应该工作。
只是用这个
element.getAttributeNode("class").value += " antherClass";
注意空间,以避免将旧班与新班级混在一起
您可以使用不同的内置方法以相同的方式添加和删除多个类:
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');