使用 setInterval() 方法: 它接受两个参数,一个函数和一个整数。此方法使用 clearInterval() 方法终止。
使用 requestAnimationFrame() 方法: 当屏幕准备好接受下一次重绘时,此方法运行该函数。它需要一个参数函数。当我们递归调用这个方法时,动画效果就会发生。预期的动画是逐帧创建的,并且在浏览器准备好时调用每一帧。
anime = setInterval(show, t); //It calls the function show after every t milliseconds clearInterval(anime); //It terminates above process
<html> <head> <script type = "text/javascript"> var img = null; function init(){ img = document.getElementById('myimg'); img.style.position = 'relative'; img.style.left = '50px'; } function moveRight(){ img.style.left = parseInt( img.style.left) + 100 + 'px'; } window.onload = init; </script> </head> <body> <form> <img id = "myimg" src = "train1.png" /> <center> <p>Click the below button to move the image right</p> <input type = "button" value = "Click Me" onclick = "moveRight();" /> </center> </form> </body> </html>
<html> <head> <title>JavaScript Animation</title> <script type = "text/javascript"> var anime ; function init(){ img = document.getElementById('myimg'); img.style.position = 'relative'; img.style.left = '0px'; } function towardRight(){ img.style.left = parseInt(img.style.left) + 10 + 'px'; anime = setTimeout(towardRight,50); } function stop() { clearTimeout(anime); img.style.left = '0px'; } window.onload = init; </script> </head> <body> <form> <img id = "myimg" src = "train1.png" /> <center> <h2 style="color:darkblue;">Click the following buttons to handle animation</h2> <input type="button" value="Start" onclick = "towardRight();" /> <input type = "button" value="Stop" onclick = "stop();" /> <center> </form> </body> </html>
<html> <head> <script type = "text/javascript"> if(document.images) { var img1 = new Image(); img1.src = "cat.jpg"; var img2 = new Image(); img2.src = "tiger.jpg"; } </script> </head> <body> <center> <a href = "#" onMouseOver = "document.myImg.src = img2.src;" onMouseOut = "document.myImg.src = img1.src;"> <img name = "myImg" src = "cat.jpg" /> </a><br><br><br> <h1>Move your mouse over the image to see the result</h1> </center> </body> </html>