匀速运动反向返回

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Document</title>     <style>         div {             width: 100px;             height: 100px;             background-color: #000;             position: absolute;             top: 0;         }         #box1{             left: 0;         }         #box2{             left: 1100px;             top: 100px;         }     </style> </head> <body>     <div id="box1"></div>     <div id="box2"></div>     <script>
        move(box1 , 1100 , 20 ) ;
        move(box2 , 0 , 35) ;

        function move(ele , end , speed ) {             var start = ele.offsetLeft ;             // 判断speed是正数还是负数  -- 由起点和终点的位置来决定             speed = (end - start > 0) ? speed : -speed ;             var t = setInterval(function(){                 start += speed ;                 ele.style.left = start + 'px' ;                 // 什么时候清除定时器   剩下的宽度少于一个speed                 if(Math.abs(end - start) < Math.abs(speed)) {                     clearInterval(t) ;                     start = end ;                      ele.style.left = start + 'px' ;                 }             },40)         }     </script> </body> </html>
上一篇:JQuery01


下一篇:微信小程序音频播放