对 css 中类的优先级感到困惑,我知道最后添加的类具有最高优先级,但是这里 就我而言,我认为我错了,我正在向 div 动态添加类,但类无法正常工作
<p>Click the button to add the "mystyle" class to DIV.</p>
<script>
function myFunction() {
document.getElementById("myDIV").classList.add("mystyle","hello");
}
</script>
<style>
.hello{
background-color: blue;
}
.mystyle {
background-color: red;
}
</style>
为什么 div 显示红色而不是蓝色?
最佳答案
你的 div
由于您的样式声明顺序,是红色而不是蓝色:
.hello {
background-color: blue;
}
.mystyle {
background-color: red;
}
CSS 特异性不依赖于将类应用到元素的顺序,而是依赖于在样式中声明类的顺序。在这种情况下,您已声明 .hello
然后.mystyle
, 意思是 .mystyle
与 .hello
相比具有高特异性因此,您会得到红色背景。
关于javascript - 添加动态类时的 Css 类优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37748305/