问题描述:请使用JavaScript相关知识实现小球在固定范围内向左向右移动,并实现点击开始按钮小球移动,点击暂停按钮小球停止移动。
关键代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } #ball { width: 100px; height: 100px; background-color: rgb(4, 59, 15); border-radius: 50%; position: absolute; left: 50px; top: 100px; } #wall_l { width: 1px; height: 300px; position: absolute; top: 50px; left: 49px; background-color: brown; } #wall_r { width: 1px; height: 300px; position: absolute; top: 50px; left: 1000px; background-color: brown; } #btndiv{ width: 400px; height: 50px; margin-left: 300px; } #btndiv button{ padding: 0px 20px; margin: 0px 10px; } </style> </head> <body> <div id="ball"></div> <div id="wall_l"></div> <div id="wall_r"></div> <div id="btndiv"> <button>向右</button> <button>向左</button> <button>开始</button> <button>暂停</button> </div> <script> var ball = document.querySelector('#ball'); var wall_l = document.querySelector('#wall_l'); var wall_r = document.querySelector('#wall_r'); var btns = document.querySelectorAll('button'); // 向右 btns[0].onclick = function () { mover(); } var timer; function mover() { var speed = 7; //偏移量 var target = wall_r.offsetLeft - 100; // 结束位置 clearInterval(timer); timer = setInterval(function () { // 获得当前位置 var l = ball.offsetLeft; var newl = l + speed; if (newl > target) { newl = target; } ball.style.left = newl + 'px'; if (newl == target) { // clearInterval(timer); // if (move()) { movel(); // } } }, 25) } // 向左 btns[1].onclick = function () { movel(); } function movel() { var speed = 7; //偏移量 var target = wall_l.offsetLeft; // 结束位置 clearInterval(timer); timer = setInterval(function () { // 获得当前位置 var l = ball.offsetLeft; var newl = l - speed; if (newl < target) { newl = target; } ball.style.left = newl + 'px'; if (newl == target) { clearInterval(timer); // if (move()) { mover(); // } } }, 25) } //左右移动 btns[2].onclick = function () { move(); } function move() { mover(); } btns[3].onclick = function () { clearInterval(timer); } </script> </body> </html>
运行效果: