我正在尝试更改 :hover
中 .box div 的颜色选择器,我只能在输入 !important
时让它工作CSS 规则旁边的标志。有更简洁的方法吗?
<!DOCTYPE html>
<html>
<head>
<style id="styles" type="text/css">
.box:hover {
background-color:blue;
}
</style>
</head>
<body onload="init()">
<script type="text/javascript">
function init() {
for (var i=0;i<500;i++) {
document.body.innerHTML += "<div class='box' style='display:block;width:100px;height:100px;background-color:red;float:left;'></div>";
}
}
</script>
</body>
</html>
最佳答案
style="..."
属性中定义的样式比样式表中定义的任何样式都具有更高的特异性。
您应该改为这样定义您的样式:
<style>
.box {
display:block;
width:100px;
height:100px;
background-color:red;
display:inline-block; /* better than float:left for your usage */
}
.box:hover {background-color:blue}
</style>
你也不应该将 +=
与 .innerHTML
一起使用。
for( var i=0; i<500; i++) {
document.body.appendChild(document.createElement('div')).className = "box";
}
关于javascript - 如何在 JS 生成的内容上使用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22483658/