Par*_*ain 2 html javascript css
与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>
Run Code Online (Sandbox Code Playgroud)
为什么div显示红色而不是蓝色?
div由于你的风格声明顺序,你是红色而不是蓝色:
.hello {
background-color: blue;
}
.mystyle {
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
CSS特异性不依赖于将类应用于元素的顺序,而是依赖于在样式中声明类的顺序.在这种情况下,你都宣称.hello然后.mystyle,意义.mystyle已高特异性相比.hello,因此,你得到的红色背景.