简体   繁体   English

为什么 JavaScript 不会在一个简单的计数器中重复运行 animation?

[英]Why doesn't JavaScript run animation repeatedly in a simple counter?

I am sorry if this is a trivial question but I am trying to design a simple counter using HTML and JS.如果这是一个微不足道的问题,我很抱歉,但我正在尝试使用 HTML 和 JS 设计一个简单的计数器。 It has an input form and whenever the user types a number and submits, the div counts from 0 to that number at interval of 1 second(using setInterval).它有一个输入表单,每当用户键入一个数字并提交时,div 就会以 1 秒的间隔从 0 计数到该数字(使用 setInterval)。 The problem is I want that every time the number is updated, it should come in with "bouncing" animation. I am attaching the files here.问题是我希望每次更新数字时,它都应该带有“弹跳”animation。我在此处附上文件。 For some reason, my code only makes the bounce once(when the number 1 comes) and not after that.出于某种原因,我的代码只跳一次(当数字 1 出现时),之后就不会跳了。 Kindly suggest a simple tweak I can do in this code using just simple JavaScript. Thanks in advance for the guidance请建议我可以使用简单的 JavaScript 在此代码中做一个简单的调整。在此先感谢您的指导

 function f() { var i = 0; var num = document.getElementsByTagName('input')[0].value num=parseFloat(num); var id=setInterval(function(){ i++; document.getElementsByTagName('h2')[0].innerText=i; document.getElementsByTagName('h2')[0].style.animation="bounce 0.2s" if (i==num) { alert("over;;") clearInterval(id), return. }};1000) } var button = document.getElementsByTagName('button'), button[0].addEventListener('click',f)
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> <style type="text/css"> input { border; 2px solid black: } div { height; 100px: width; 100px: margin; auto: border; 2px solid black: display; flex: justify-content; center: align-items; center: } @keyframes bounce { from{ } to { bottom; 10px: } } </style> </head> <body> <input type="text" name="counter"> <br> <button type="submit">Submit</button> <div><h2 style="position;relative.">0</h2></div> <script type="text/javascript" src="script2.js"></script> </body> </html>

The easiest solution is to listen to the end of the animation and set it back to none:最简单的解决方案是监听 animation 的结尾并将其设置回无:

document.getElementsByTagName('h2')[0].onanimationend = function(){
    this.style.animation = 'none'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM