[英]classList.add() is not activated immediately in clicked event
function highlight1(){ document.getElementById("div1").classList.add("red"); } function highlight2(){ document.getElementById("div2").classList.add("red"); } function highlight3(){ document.getElementById("div3").classList.add("red"); }
div{ display: inline-block; border: 1px solid black; height: 100px; width: 100px; } div:hover{ background: yellow; } .red{ background: red; }
<div id="div1" onclick="highlight1()">Division</div> <div id="div2" onclick="highlight2()">Division</div> <div id="div3" onclick="highlight3()">Division</div>
I'm new to CSS and I have two questions for the code. 我是CSS的新手,我对代码有两个问题。
Your :hover
is making hovered div
s, even .red
div
s, appear hovered (yellow) instead of red. 你的
:hover
正在制作悬停的div
,即使是.red
div
,也会出现徘徊(黄色)而不是红色。 You could make hovered .red
divs red as well if you wanted. 如果你愿意的话,你也可以
.red
红色.red
divs red。
If you only want one to be red at a time, you can remove .red
from all divs before using classList.add
. 如果你只想要一个是红色的时间,你可以删除
.red
从所有div使用前classList.add
。
It would also be more appropriate to use classes than individual id
s, because the elements are part of a collection rather than being unique in some way: 使用类比单个
id
更合适,因为元素是集合的一部分,而不是以某种方式是唯一的:
const divs = document.querySelectorAll('.box'); function reset(i) { divs.forEach(div => div.classList.remove("red")); divs[i].classList.add('red'); }
.box { display: inline-block; border: 1px solid black; height: 100px; width: 100px; } .box:hover { background: yellow; } .red, .red:hover { background: red; }
<div class="box" onclick="reset(0)">Division</div> <div class="box" onclick="reset(1)">Division</div> <div class="box" onclick="reset(2)">Division</div> </html>
You can do this by applying, div.red:hover
by doing this you are actually overriding div:hover
with div.red:hover
prioritizing div.red:hover
你可以通过应用,
div.red:hover
div:hover
这样做你实际上覆盖了div:hover
with div.red:hover
优先级div.red:hover
function highlight1(){ document.getElementById("div1").classList.add("red"); } function highlight2(){ document.getElementById("div2").classList.add("red"); } function highlight3(){ document.getElementById("div3").classList.add("red"); }
div{ display: inline-block; border: 1px solid black; height: 100px; width: 100px; } div:hover{ background: yellow; } div.red:hover,.red{ background: red; }
<div id="div1" onclick="highlight1()">Division</div> <div id="div2" onclick="highlight2()">Division</div> <div id="div3" onclick="highlight3()">Division</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.