为什么关键帧动画会重复不止一次?
Why does keyframe animation repeat more than once?
.a.b{
border: 2px solid red;
animation-name: appear;
animation-duration: 1s;
animation-iteration-count: 1;
}
@keyframes appear{
from{opacity:0;
transform:rotateZ(20deg);
top:100;}
to{opacity:1;
top:0;
transform:rotate(0);}
}
@keyframes zoomer{
from{
opacity:0.5;
}
to{
opacity:1;
}
}
.a.b:hover{
animation: zoomer 1s linear 1;
}
<html>
<head>
</head>
<body>
<div>
<h1 class="a b">hello world</h1>
</div>
</body>
</html>
在上面的代码片段中,为什么当我使用悬停时 @keyframes
动画会重复?迭代次数指定为1.
我的猜测是,与 <h1>
标签关联的 class 在我们悬停时发生变化,然后在我们移开鼠标时再次发生变化。但是我们该如何解决呢?
动画正在触发,因为 :hover
伪 class 覆盖了 <h1>
的 animation
属性。当伪 class 被移除时,animation
属性 "changes" 再次回到其原始值,这会触发动画。
有几种方法可以解决此问题。如果你想让 <h1>
在加载时有动画效果,但再也不想了,考虑创建一个单独的 class:
.a.b.onload {
animation-name: appear;
animation-duration: 1s;
animation-iteration-count: 1;
}
然后在Javascript中,等待初始动画完成1秒后移除class:
window.addEventListener("DOMContentLoaded", () => {
setTimeout( () => {
document.querySelector(".a.b").classList.remove("onload")
}, 1000);
});
.a.b{
border: 2px solid red;
animation-name: appear;
animation-duration: 1s;
animation-iteration-count: 1;
}
@keyframes appear{
from{opacity:0;
transform:rotateZ(20deg);
top:100;}
to{opacity:1;
top:0;
transform:rotate(0);}
}
@keyframes zoomer{
from{
opacity:0.5;
}
to{
opacity:1;
}
}
.a.b:hover{
animation: zoomer 1s linear 1;
}
<html>
<head>
</head>
<body>
<div>
<h1 class="a b">hello world</h1>
</div>
</body>
</html>
在上面的代码片段中,为什么当我使用悬停时 @keyframes
动画会重复?迭代次数指定为1.
我的猜测是,与 <h1>
标签关联的 class 在我们悬停时发生变化,然后在我们移开鼠标时再次发生变化。但是我们该如何解决呢?
动画正在触发,因为 :hover
伪 class 覆盖了 <h1>
的 animation
属性。当伪 class 被移除时,animation
属性 "changes" 再次回到其原始值,这会触发动画。
有几种方法可以解决此问题。如果你想让 <h1>
在加载时有动画效果,但再也不想了,考虑创建一个单独的 class:
.a.b.onload {
animation-name: appear;
animation-duration: 1s;
animation-iteration-count: 1;
}
然后在Javascript中,等待初始动画完成1秒后移除class:
window.addEventListener("DOMContentLoaded", () => {
setTimeout( () => {
document.querySelector(".a.b").classList.remove("onload")
}, 1000);
});