【问题标题】:Why does keyframe animation repeat more than once?为什么关键帧动画会重复多次?
【发布时间】:2020-04-11 04:42:10
【问题描述】:

.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>

在上面的代码sn-p中,为什么我使用hover时@keyframes动画会重复?迭代次数指定为1。

我的猜测是,与&lt;h1&gt; 标签关联的类在我们悬停时会发生变化,然后在我们移开鼠标时再次发生变化。但是我们要如何解决呢?

【问题讨论】:

  • 你能解释一下你所说的“重复”是什么意思吗?您的意思是“出现”动画在加载时发生,然后在光标移出元素后再次发生?
  • @FunkyDelPueblo 是的

标签: html css css-animations keyframe


【解决方案1】:

动画正在触发,因为:hover 伪类覆盖了&lt;h1&gt;animation 属性。当伪类被移除时,animation 属性再次“改变”,回到它的原始值,这会触发动画。

有几种方法可以解决此问题。如果您想让 &lt;h1&gt; 加载动画,但再也不想加载,请考虑创建一个单独的类:

.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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多