代码:
<!DOCTYPE HTML><html><head> <meta charset="utf-8"> <title>无标题文档</title> <style> #div1 { width: 100px; height: 100px; background: #ff4b46; position: absolute; left: 100px; top: 50px; } #vertical_line { width: 1px; height: 300px; position: absolute; left: 300px; top: 0; background: black; } </style> <script> var timer = null; function startMove(iTarget) { clearInterval(timer); timer = setInterval(function () { var oDiv = document.getElementById("div1"); var speed = 0; if (oDiv.offsetLeft < iTarget) { speed = 7; } else { speed = -7; } if (Math.abs(iTarget - oDiv.offsetLeft) <= 7) { clearInterval(timer); oDiv.style.left = iTarget + ‘px‘; } else { speed = 7; oDiv.style.left = oDiv.offsetLeft + speed + "px"; document.title = oDiv.offsetLeft + ‘,‘ + speed; } }, 30); } </script></head><body><input type="button" value="开始运动" onclick="startMove(300)"> <div id="div1"> </div><div id="vertical_line"></div> </body></html>
运行结果:
初始界面:
点击鼠标之后界面:
时间: 2024-10-10 04:05:18