核心提示:代码实现:Div加速减速!DOCTYPE htmlhtml head meta charset=utf-8 / title/title /head style body{margin: 0;pa...
代码实现:Div加速减速
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style> body{margin: 0;padding: 0;} p{width: 100px;height: 100px;background: red;position: absolute;left: 0px;top: 0px;z-index: 100;} button{width: 50px;height: 30px;background: #000;margin-top: 120px;color: #fff;} #line{width: 20px;height: 300px;background: green;position: absolute;left: 800px;z-index: 10;} </style> <body> <p id="box"></p> <button id="btn">运动</button> <p id="line"></p> </body> <script> var box = document.getElementById("box"); var btn = document.getElementById("btn"); var line = document.getElementById("line"); var Target = line.offsetLeft; var timer =null; btn.onclick = function(){ clearInterval(timer); timer = setInterval(function(){ var oBox = box.offsetLeft; var speed = (Target - oBox)/8; speed = speed>0? Math.ceil(speed):Math.floor(speed); box.style.left = oBox + speed+"px" if(speed == 0){ clearInterval(timer) } console.log(speed) },30) } </script> </html>