Div 定时移动

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <title></title>
 7     <script src="js/jquery-1.11.1.js" type="text/javascript"></script>
 8 </head>
 9 <style>
10   button{width:80px; height:50px; margin: 10px;}
11   #divRed{width: 100px; height: 100px; background-color: red; position: absolute; top:90px; left: 0; }
12 </style>
13 <body>
14     <button type="text" id="btnLeft">左移动</button>
15     <button type="text" id="btnRight">右移动</button>
16     <div id="divRed"></div>
17     <script  type="text/javascript" charset="utf-8">
18        $(function(){
19               var btnL = $('#btnLeft');
20               var btnR = $('#btnRight');
21               var divR = $('#divRed');
22                btnL.click(function(){
23                MoveDiv(divR,'left',10,0)
24              });
25              btnR.click(function(){
26                MoveDiv(divR,'left',10,500)
27              });
28                  function MoveDiv(obj,pos,dir,targer){
29                      dir=parseInt(obj.css(pos)) < targer ? dir: -dir;
30                        clearInterval(obj.timer)
31                      obj.timer=setInterval(function(){
32                         var  speed=parseInt(obj.css(pos))+dir;
33                         console.log(obj,pos);
34                        if(speed > targer && dir > 0 ||  speed < targer && dir < 0  ){ speed = targer;}
35                             obj.css(pos,speed +'px');
36                           if(speed== targer){  clearInterval(obj.timer)}
37  
38                        },30);  
39 
40                  }
41 
42             
43         
44           
45              
46        })
47    </script>  
48 </body>
49 </html>
原文地址:https://www.cnblogs.com/deveil/p/6208360.html