我想在单击另一个元素时突出显示某些 HTML 元素。使用 CSS 的经典解决方案似乎仅如下所示,使用以下 HTML,
<!DOCTYPE html>
<html>
<body>
<div>
There are <a href="#fermions">Fermions</a>
and <a href="#bosons">Bosons</a>.
<div class="highlightable" id="fermions">
Bosons are very social particles!
</div>
<div class="highlightable" id="bosons">
Fermions only goes out as a couple!
</div>
</div>
</body>
</html>
和下面的 CSS
@keyframes highlight {
0% {
background: LightSkyBlue;
}
100% {
background: none;
}
}
.highlightable:target {
animation: highlight 1s;
}
这是一个fiddle implementing this .当我点击“Fermions”时,div
“Fermions only out out as a couple!”强调。好的!当我再次点击“费米子”时,它不再突出显示。但是,如果我点击“Bosons”,从而突出显示另一个 div
,然后再次在 Fermions 上,然后再次突出显示带有 Fermions 的 div
。
谁能解释一下这是怎么回事?总是点击突出显示相应的 div
以使用 Javascript 的唯一解决方案吗?
最佳答案
对所见内容的解释:
如果您的浏览器当前指向此地址:
mysite.com/mypage/
然后你点击<a href="#fermions">
,您的浏览器现在将指向:
mysite.com/mypage/#fermions
这将触发 :target
伪类动画。
如果您现在单击 <a href="#fermions">
再次......你不会去任何地方 - 因为你已经在那里。
所以动画不会被触发。
实现这个效果(仅限 CSS):
我明白你可能想要一种纯 CSS 的方式来产生这种效果,但是......你只能(某种程度上)通过 CSS 使用 :focus
响应用户点击和 :target
.在这两种情况下,您都会看到,一旦进入给定状态(并且动画已运行一次),您将保持该状态(并且动画不会再次运行),直到您主动更改状态。
就是说,您可以通过 CSS 响应用户鼠标悬停,使用 :hover
来产生您想要的效果伪类。
工作示例:
[href="#fermions"]:hover ~ #fermions,
[href="#bosons"]:hover ~ #bosons {
animation: highlight 1.2s ease-out 0.15s;
}
@keyframes highlight {
0% {background: LightSkyBlue;}
100% {background: none;}
}
<div>
There are <a href="#fermions">Fermions</a> and <a href="#bosons">Bosons</a>.
<p class="highlightable" id="bosons">
Bosons are very social particles!</p>
<p class="highlightable" id="fermions">Fermions only goes out as a couple!</p>
</div>
关于css - :target pseudo-element triggers only on the first click内的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433199/