<分区>
标签 javascript css
<分区>
我有这个代码:
var image = button.getElementsByTagName("span")[0];
if (isEnabled) {
image.style.color = "#BBB"
else {
image.style.color = "#AAA"
有人可以给我一些建议,告诉我如何不直接设置颜色,而是将按钮设置为启用第 3 级,然后再将其设置为禁用第 3 级吗?
请注意,我的按钮目前有这样的类:
class="fa fa-bold"
class="fa fa-arrow"
等等
所以我需要前两个类保持不变。然后我需要能够设置成这样:
class="fa fa-bold enabled"
class="fa fa-bold disabled"
class="fa fa-bold enabled"
等等
最佳答案
要向图像添加新类 myClass
,请使用 add()
:
Adds a class to an element's list of classes. If class already exists in the element's list of classes, it will not add the class again.
image.classList.add('myClass')
要删除类,请使用 remove()
Removes a class from an element's list of classes in a safe manner. Errors are not thrown If the class does not exist.
image.classList.remove('myClass')
要切换
类,请使用toggle()
If the name exists within the element's classList, it will be removed. If name does not exist, it will be added.
image.classList.toggle('myClass') // If exists, remove, if not add
要检查元素是否有类,使用contains()
Checks if an element's list of classes contains a specific class .
if (image.classList.contains('myClass')) {
alert('HasClass myClass');
} else {
alert('Dont have class');
}
CSS
.myClass {
color: #bbb;
}
关于javascript - 如何使用 javascript 更改按钮的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227630/