英文:
How to refresh keyframe animation by click in js?
问题
我想制作一个每次点击按钮都会启动的动画。它能够工作,但只能运行一次。再次按下按钮时没有任何反应。尝试删除并再次添加相同的类,但没有帮助。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
body{
margin: 0;
padding:0;
width: 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>
以上是您提供的代码的翻译。
英文:
I want make animation which started every click by button. It is work but only once. When pressed again nothing happens. Tried to remove and add the same class again. Did not help.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!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>
<!-- end snippet -->
答案1
得分: 1
你必须在动画结束后移除该类。然后,当你再次添加该类时,动画将再次触发。
在这里,我在1秒后移除了该类,因为动画持续时间为1秒。
英文:
You must remove the class after the animation ends. Then, when you add the class again, the animation will trigger again.
Here, I have removed the class after 1 second, because the animation duration is 1 second.
<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-html -->
<!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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论