点击“向右”按钮,红色的#red区块开始向右缓冲运动,抵达到黑色竖线位置自动停止,再次点击“向右”#red区块也不会再运动。点击“向左”按钮,红色的#red区块开始向左缓冲运动,抵达到蓝色竖线位置自动停止,再次点击“向左”#red区块也不会再运动。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>JS小案例:缓冲运动</title> <style> #red { width: 200px; height: 200px; background: red; position: absolute; top: 50px; left: 200px; } .black { position: absolute; width: 1px; height: 200px; left: 900px; background: black; top: 50px; } .blue { position: absolute; width: 1px; height: 200px; left: 200px; background: blue; top: 50px; } </style> <script> //补充代码 </script> </head> <body> <input type='button' value='向右' id='btn' /> <input type='button' value='向左' id='btn-left' /> <div id='red'></div> <div class='black'></div> <div class='blue'></div> </body> </html>
参考代码:
window.onload = function () { var oDiv = document.getElementById('red'); var oBtn = document.getElementById('btn'); var oBtnLeft = document.getElementById('btn-left'); var timer = null; function startMove(iTarget) { clearInterval(timer); timer = setInterval(function () { var speed = (iTarget - oDiv.offsetLeft) / 30; speed=speed>0?Math.ceil(speed):Math.floor(speed); if (oDiv.offsetLeft == iTarget) { clearInterval(timer) } else { oDiv.style.left = oDiv.offsetLeft + speed + 'px'; } }, 30) } oBtn.onclick = function () { startMove(700); } oBtnLeft.onclick = function () { startMove(200); } }
来源:https://www.cnblogs.com/f6056/p/11281821.html