只有当鼠标悬停在某个元素上时,我才试图运行CSS动画。基本上,如果鼠标悬停在父元素容器上,我希望子元素光只有在鼠标悬停时才能运行其动画。我想通过JavaScript/jQuery来实现这一点,因为我不确定仅用CSS就能做到这一点。我也是JavaScript的新手!
.light {
position: absolute;
transform: translate(-200%, 20%);
width: 4px;
height: 4px;
border-radius: 5px;
background: #0f0;
filter: hue-rotate(80deg);
z-index: 2;
animation: light 1s linear infinite;
}
@keyframes light {
*some animation*
}<div class="container">
<div class="light"></div>
</div>
我很抱歉,如果这是一个基本的问题,但我已经研究了几个小时,但没有成功!
发布于 2021-05-06 21:26:08
使用:hover
.light {
width: 40px;
height: 40px;
border-radius: 5px;
background: green;
}
.container {
border: 1px dotted red;
}
.container:hover > .light {
animation: light 1s linear infinite;
}
@keyframes light {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}<div class="container">
<div class="light"></div>
</div>
发布于 2021-05-06 21:30:59
如果您希望用JavaScript来实现这一点,您可以在mouseover上添加一个hover类,并将关键帧动画添加到mouseover中的.light.hover中,如下所示:
var target = document.querySelector(".light");
target.addEventListener("mouseover", mouseOver, false);
target.addEventListener("mouseout", mouseOut, false);
function mouseOver() {
target.classList.add("hover")
}
function mouseOut() {
target.classList.remove("hover")
}.light {
width: 100px;
height: 100px;
border-radius: 5px;
background: #0f0;
}
.light.hover {
animation: light 3s linear infinite;
}
@keyframes light {
from {
filter: hue-rotate(0);
}
to {
filter: hue-rotate(180deg);
}
}<div class="light"></div>
但是CSS的方式仅仅是使用:
.light {
width: 100px;
height: 100px;
border-radius: 5px;
background: #0f0;
}
.light:hover {
animation: light 3s linear infinite;
}https://stackoverflow.com/questions/67426112
复制相似问题