<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin:0; padding:0; } #ball { 50px; height:50px; background-color: red; border-radius: 50%; position:absolute; left:0; top:200px; } </style> </head> <body> <input type="button" value="开始" id="btn"> <div id="ball"></div> <script> // 获取dom对象 var $btn = document.querySelector('#btn'); var $ball = document.querySelector('#ball'); // 设置速度 var topSpeed = 5; var leftSpeed = 5; // 点击按钮 小球开始运动 $btn.onclick = function () { // 设置定时器 setInterval(function () { // 获取小球最大移动的宽,高 var maxTop = document.documentElement.clientHeight - $ball.offsetHeight; var maxLeft = document.documentElement.clientWidth - $ball.offsetWidth; // 小球超出可视区让其速度取反 if ($ball.offsetTop < 0 || $ball.offsetTop > maxTop) { topSpeed *= -1; } else if ($ball.offsetLeft < 0 || $ball.offsetLeft > maxLeft) { leftSpeed *= -1; } // 通过改变小球的left,top属性使其运动 $ball.style.left = $ball.offsetLeft + leftSpeed + "px"; $ball.style.top = $ball.offsetTop - topSpeed + "px"; }, 20) } </script> </body> </html>
右边没录好