<!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>
* {
padding: 0;
margin: 0;
}
div {
width: 28px;
height: 28px;
border-radius: 50%;
background-color: red;
position: absolute;
left: 0;
top: 200px;
}
</style>
</head>
<body>
<button id="fly">Flying</button>
<div id="ball"></div>
<script>
function $(id){
return document.getElementById(id);
}
var ball = $('ball');
var speedX = 10;speedY = -5;
var totalW = document.documentElement.clientWidth||document.body.clientWidth;
// 或window.innerWidth
var totalH = document.documentElement.clientHeight||document.body.clientHeight;
// 或window.innerHeight
var timer = setInterval(function(){
ball.style.left = ball.offsetLeft+speedX+'px';
ball.style.top = ball.offsetTop+speedY+'px';
var maxW = totalW - ball.offsetWidth;
var maxH = totalH - ball.offsetHeight;
if(ball.offsetLeft>=maxW){
ball.style.left = maxW+'px';
speedX*=-1;
}else if(ball.offsetLeft<=0){
ball.style.left = 0+'px';
speedX*=-1;
}
if(ball.offsetTop>=maxH){
ball.style.top = maxH+'px';
speedY*=-1;
}else if(ball.offsetTop<=0){
ball.style.top = 0+'px';
speedY*=-1;
}
},20)
</script>
</body>
</html>
如下图