<!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;
background:url(ball.jpg) no-repeat center center;
background-size:100% 100%;
}
</style>
</head>
<body>
<button id="fly">Flying</button>
<div id="ball"></div>
<script>
function $(id){
return document.getElementById(id);
}
var speedX = 6,speedY = -16;
var ball = $('ball');
var totalH = window.innerHeight;
var totalW = window.innerWidth;
var fly = $('fly');
fly.onclick = function(){
clearInterval(timer);
var timer = setInterval(function(){
ball.style.top = ball.offsetTop + speedY + 'px';
ball.style.left = ball.offsetLeft + speedX + 'px';
var maxH = totalH - ball.offsetHeight;
var maxW = totalW - ball.offsetWidth;
if(ball.offsetTop>=maxH){
ball.style.top = maxH+'px';
speedY*=-0.9;
speedX--;
if(speedX<=0){
speedX = 0;
}
if(Math.abs(speedY)<=1){
ball.style.top = maxH+'px';
console.log(speedY)
clearInterval(timer);
}
}
speedY++;
},20)
}
</script>
</body>
</html>
如下图