javascript - 如何使用 javascript 更改按钮的类?

标签 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"

等等

最佳答案

使用classList

要向图像添加新类 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/

上一篇:html - CSS子菜单打扰了父级

下一篇:javascript - 悬停时更改对象的大小

相关文章:

javascript - 如何在 JSON 中创建空格

javascript - Sails js 中未定义 "Invalid attributes sent to undefined"

javascript - 无法将 Prop 中的功能传递给组件 | react

css - 高度/宽度 : 100% and --webkit-fill-available 之间有什么区别

css - 媒体查询最小高度显示 anchor 顶部链接

html - 纯 CSS3 显示/隐藏带过渡的全高 div

javascript - 如何创建一个也是输入文本框的选择列表?

javascript - 在回显时连接 PHP 和 JS

javascript - 滚动时, Logo 颜色发生变化,但向上滚动时它保持不变

jQueryUI 对话框 VS twitter bootstrap 覆盖,将一个放在另一个之上