.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>
标记关联的类在悬停时会更改,然后在移开鼠标时会再次更改。但是我们要如何解决?
动画正在触发,因为:hover
伪类覆盖了<h1>
的animation
属性。删除伪类后,animation
属性再次“更改”,恢复为其原始值,从而触发了动画。
您可以通过几种方法来解决此问题。如果您想让<h1>
加载动画,但永远不要再加载,请考虑创建一个单独的类:
.a.b.onload {
animation-name: appear;
animation-duration: 1s;
animation-iteration-count: 1;
}
然后用Javascript,在等待1秒钟以完成初始动画之后删除类:
window.addEventListener("DOMContentLoaded", () => {
setTimeout( () => {
document.querySelector(".a.b").classList.remove("onload")
}, 1000);
});