javascript - 如何使用javascript更改类名?

标签 javascript html css

代码

window.onload = function() {
  var refButton = document.getElementById("old");
  refButton.onmouseover = function() {
    refButton.className = 'newClass';
  }
};
.newClass {
  color: white;
}
#old {
  color: blue;
}
<div id="old">
  Hello
</div>

如果我输入 style.color="red" 而不是 ClassName,那么代码就可以工作。

请问是什么问题

最佳答案

是因为CSS specificity ,所以只需将 #old 添加到您的 .newClass

  • .newClass 具有特殊性:0 0 1 0
  • #old 具有特殊性:0 1 0 0

因此 #old 更具体。

使用 #old.newClass 你会得到 0 1 1 0 这将更具体并将应用你想要的新样式。

可以计算CSS特异性here

window.onload = function() {
  var refButton = document.getElementById("old");
  refButton.onmouseover = function() {
    refButton.className = 'newClass';
  }
};
#old.newClass {
  color: red;
  /* changed for demo */
}
#old {
  color: blue;
}
<div id="old">
  Hello
</div>

关于javascript - 如何使用javascript更改类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126924/

相关文章:

javascript - HTML如何将&lt;input type ="number">的值设置为无穷大

javascript - 从 Express 应用返回 JSON : Uncaught (in promise) SyntaxError: Unexpected end of input

javascript - jQuery.data() 适用于 Mac OS WebKit,但不适用于 iPhone OS?

javascript - javascript 新手,为什么我的按钮不起作用?

javascript - 以编程方式在 HTML5 SVG 中添加位图图像

python - 在for循环中更改django表单的ID

html - 显示 : flex and new line for captions - what is the proper way?

javascript - 设置动态 div 的网格

css - 将透明图像放在背景图像上

css - 自动换行在 Firefox 中不起作用,尝试了一切