如何通过单击JS刷新关键帧动画?

时间:2020-01-06 15:23:56

标签: javascript css-animations

我想要制作动画,该动画每次按一次按钮就会开始。这是工作,但只有一次。再按一次则什么也没有发生。试图删除并再次添加相同的类。没有帮助。

<!DOCTYPE html>
<html>
<head>
	
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<style type="text/css">
		body{
			margin: 0;
			padding:0;
			widht: 100%;
		}
	</style>
</head>
<body>
	<style>
		@keyframes red-to-black {
			0% {background: rgba(150,0,0,100);}
			100% {background: rgba(0,0,0,100);}
		}
		.RedBack {
			animation: red-to-black 1s ease-out;
		}	
	</style>
	<div id="back" style = "background: black; width: 100vw; height:100vh;">
		<button onclick="document.getElementById('back').classList.add('RedBack');">Hello!</button>
	</div>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

动画结束后,您必须删除该类。然后,当您再次添加类时,动画将再次触发。

在这里,我在1秒后删除了该类,因为动画持续时间是1秒。

<!DOCTYPE html>
<html>
<head>
	
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<style type="text/css">
		body{
			margin: 0;
			padding:0;
			widht: 100%;
		}
	</style>
</head>
<body>
	<style>
		@keyframes red-to-black {
			0% {background: rgba(150,0,0,100);}
			100% {background: rgba(0,0,0,100);}
		}
		.RedBack {
			animation: red-to-black 1s ease-out;
		}	
	</style>
	<div id="back" style = "background: black; width: 100vw; height:100vh;">
		<button onclick="onClick()">Hello!</button>
	</div>
    <script>
        function onClick() {
            document.getElementById('back').classList.add('RedBack');
            setTimeout(() => {
               document.getElementById('back').classList.remove('RedBack');
            }, 1000)
        }
    </script>
</body>
</html>