如何在 JavaScript 中添加/删除类? [英] How to add/remove a class in JavaScript?

查看:19
本文介绍了如何在 JavaScript 中添加/删除类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 element.classList IE 9 和 Safari-5 不支持,有什么替代的跨浏览器解决方案?

Since element.classList is not supported in IE 9 and Safari-5, what's an alternative cross-browser solution?

无框架.

解决方案必须至少适用于 IE 9Safari 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):

  1. 如何添加和删除css类

添加和删除带有动画的类

添加删除类?

推荐答案

在没有框架/库的情况下使用类的一种方法是使用属性 Element.className,它获取和设置类的值指定元素的属性."(来自 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆