<code class="language-html"> <meta charset=" utf-8"> <title>javascript实现的简单动画</title> <style type="text/css"> #mydiv { width:50px; height:50px; background-color:green; position:absolute; } </style> <script type="text/javascript"> window.onload=function() { var mydiv=document.getElementById("mydiv"); var start=document.getElementById("start"); var stopmove=document.getElementById("stopmove"); var x=0; var flag; function move() { x=x+1; mydiv.style.left=x+"px"; } start.onclick=function() { clearInterval(flag); flag=setInterval(move,20); } stopmove.onclick=function() { clearInterval(flag); } } </script> <input type="button" id="start" value="开始运动"> <input type="button" id="stopmove" value="停止运动"> <div id="mydiv"></div> </code>
在线运行
代码解释: