如何在JavaScript中添加/删除类? [英] How to add/remove a class in JavaScript?
问题描述
由于 元素。 IE9和Safari-5不支持classList
,另一种跨浏览器解决方案是什么?
Since element.classList
is not supported in IE 9 and Safari-5, what's an alternative cross-browser solution?
否框架请。
解决方案必须至少 IE 9 , Safari 5 ,FireFox 4,Opera 11.5和Chrome。
Solution must work in at least IE 9, Safari 5, FireFox 4, Opera 11.5, and Chrome.
相关文章(但不包含解决方案):
Related posts (but does not contain solution):
推荐答案
一种在没有框架/库的情况下玩的一种方式是使用属性Element.className,获取并设置指定元素的class属性的值。(从 MDN文档)。
作为 @matías- fidemraizer 在他的答案中已经提到,一旦你获得了元素的字符串,你可以使用与字符串相关的任何方法来修改它。
One way to play around with classes without frameworks/libraries would be using the property Element.className, which "gets and sets the value of the class attribute of the specified element." (from the MDN documentation).
As @matías-fidemraizer already mentioned in his answer, once you get the string of classes for your element you can use any methods associated with strings to modify it.
这是一个例如:
假设你有一个ID为myDiv的div,并且当用户点击它时,你想要添加类main__section,
Here's an example:
Assuming you have a div with the ID "myDiv" and that you want to add to it the class "main__section" when the user clicks on it,
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中添加/删除类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!