认识js运动

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>Document</title>
 6         <style>
 7             #div1{width:100px; height: 100px; background-color: red; position: absolute; left: 0px; top: 100px}
 8         </style>
 9         <script>
10             /*
11                 实现动画
12                 人眼能够识别的最小间隔 18帧  1秒18张图片
13 
14                 运动中的问题
15                 1、不会停
16                 2、速度在取某些值的时候不会停
17                 3、到达目的值以后,点击还会往前运动
18                     需要通过if...else将运动和停止分开
19                 4、重复点击,启动多个定时器,速度越来越快
20                     保证,在统一时间只能有一个定时器启动。
21 
22                     每次启动定时器之前,先将上一次的定时器关闭。
23 
24 
25                 运动框架总结:
26                     1、运动和停止分开
27                         if...else
28                     2、每次启动定时器之前,先将上一次定时器关闭。
29 
30                 
31 
32             */
33 
34             window.onload = function(){
35                 var oDiv = document.getElementById("div1");
36                 var timer = null;
37                 document.onclick = function(){
38                     var speed = 7;
39                     clearInterval(timer);
40                     timer = setInterval(function(){
41                         
42                         if(oDiv.offsetLeft >= 500){
43                             clearInterval(timer);
44                         }else{
45                             oDiv.style.left = oDiv.offsetLeft + speed + 'px';
46                         }
47                     }, 30);
48                 }
49             }
50         </script>
51     </head>
52     <body>
53         <div id = 'div1'></div>
54     </body>
55 </html>

浏览器效果:

猜你喜欢

转载自www.cnblogs.com/taohuaya/p/9623676.html
今日推荐