§ ITPOW >> 文档 >> CSS

CSS 3 动画问答-animation 执行一遍后,如何暂停(延时)再执行下一遍?

作者:vkvi 来源:ITPOW(原创) 日期:2021-8-23

animation 多个参数中,有一个延时参数,但是那个只是首次延时,我们希望每次执行后停一段时间,再继续循环下一次

这直接配置 CSS 是实现不到的,利用 JS 倒是可以轻松在实现。

<style type="text/css">
@keyframes ani {
	from { width:50px; height:50px; }
	to { width:100px; height:100px; }
}

.c1 { width:50px; height:50px; background:red; }
.c1.animation { width:100px; height:100px; animation:ani 1s ease-out; }
</style>

<div class="c1"></div>

<script>
function ani() {
	var c1 = document.querySelector(".c1");
	if (c1.className.indexOf("animation") >= 0) {
		c1.className = "c1";
		// c1.className = "c1 animation"; // 这里不能直接设
		setTimeout(ani, 0);
	}
	else {
		c1.className = "c1 animation";
		setTimeout(ani, 3000); // 延后 3 秒,除去动画的 1 秒,实则表示停顿 2 秒。
	}
}

window.onload = ani;
</script>

相关文章