简体   繁体   English

使用setInterval函数在JavaScript中创建动画

[英]Using the setInterval function to create an animation in JavaScript

I want to use the setInterval function to create an animation in JavaScript but I have encountered a problem. 我想使用setInterval函数在JavaScript中创建动画,但是遇到了问题。

I used: 我用了:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style> .main{ width:80%; margin:auot; text-align: center; } p{ position:absolute; top:0px; } </style> </head> <body> <div class="main"> <h1>bianti</h1> </div> <p id="mydiv">ssss</p> <script type="text/javascript" > var obj=document.getElementById('mydiv'); function changeStyle(){ obj.style.top=parseInt(obj.style.top)+200+'px' } setInterval(changeStyle,1000); </script> </body> </html> 

but it doesn't work. 但这不起作用。 I change the code, using the inline css and replacing the embedded css. 我使用内联CSS并替换嵌入式CSS来更改代码。 Then it works but I don't know why. 然后就可以了,但我不知道为什么。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style> .main{ width:80%; margin:auot; text-align: center; } </style> </head> <body> <div class="main"> <h1>bianti</h1> </div> <p id="mydiv" style="position:absolute;top:0;">ssss</p> <script type="text/javascript" > var obj=document.getElementById('mydiv'); function changeStyle(){ obj.style.top=parseInt(obj.style.top)+200+'px' } setInterval(changeStyle,1000); </script> </body> </html> 

Just to answer the question: 只是为了回答这个问题:

but it doesn't work 但这不起作用

The parseInt was not returning an integer value as style.top was empty. parseInt没有返回整数值,因为style.top为空。

Sample code: 样例代码:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style> .main { width: 80%; margin: auot; text-align: center; } p { position: absolute; top: 0px; } </style> </head> <body> <div class="main"> <h1>bianti</h1> </div> <p id="mydiv">ssss</p> <script type="text/javascript"> var obj = document.getElementById('mydiv'); function changeStyle() { var init = 0; if (obj.style.top) { init = parseInt(obj.style.top); } obj.style.top = init + 200 + 'px' } setInterval(changeStyle, 1000); </script> </body> </html> 

This will work. 这将起作用。 In your css make it #mydiv {... } 在您的CSS中将其设为#mydiv {...}

 var obj=document.querySelector('#mydiv');
 function changeStyle(){
    obj.style.top+= "200px";
 }
 setInterval(changeStyle,1000);

Try use this css 尝试使用此CSS

#mydiv {
        transition: all 300ms;
    }

example - https://jsfiddle.net/grinmax_/wnvnjmtr/ 示例-https://jsfiddle.net/grinmax_/wnvnjmtr/

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

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