console
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var ball = document.getElementById("ball");
var timer;
x = y = 0;xspeed = yspeed = 2;
duration = 20;
width = height = 100;
btn1.onclick = function() {
if(timer) {
return;
}
timer = setInterval(function() {
x += xspeed;
y += yspeed;
if(y >= document.documentElement.clientHeight - height) {
y = document.documentElement.clientHeight - height;
yspeed = -yspeed;
}
if(y <= 0) {
y = 0;
yspeed = -yspeed;
}
if(x >= document.documentElement.clientWidth - width) {
x = document.documentElement.clientWidth - width;
xspeed = -xspeed;
}
if(x <= 0) {
x = 0;
xspeed = -xspeed;
}
ball.style.left = x + "px";
ball.style.top = y + "px";
}, duration)
}
btn2.onclick = function() {
clearInterval(timer);
timer = null;
}
<button id="btn1">开始</button>
<button id="btn2">停止</button>
<div id="ball"></div>
#ball {
width: 100px;
height: 100px;
background-color: red;
border-radius: 70%;
position: absolute;
}