在下面的代码中,div“main”从类“main1”切换到“main2”。 测试表明新类别已应用(尺寸从 100x200 变为 200x100), 然而,新类不会覆盖预先分配给 div 的背景颜色。 这是正常行为吗?
<!DOCTYPE html>
<html>
<head>
<style>
.main1 {width:100px; height:200px; background-color:yellow;}
.main2 {width:200px; height:100px; background-color:orange;}
</style>
<script>
function start() {
document.getElementById("main").style.backgroundColor = "green";
document.getElementById("main").className = "main2";
}
</script>
</head>
<body onload="start();">
<div id="main" class="main1"></div>
</body>
</html>
最佳答案
Inline 样式(green
)比 class 样式有更高的优先级。(yellow
和 orange
。所以在这种情况下将应用内联样式,除非你有一个更先例的选择器使用 !important
关于javascript - CSS 新类不覆盖特定元素样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902949/