
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.wrapper{
width: 500px;
height: 500px;
border: 5px solid black;
margin: 0 auto;
position: relative;
}
.boll{
width: 80px;
height: 80px;
border-radius: 50%;
background-color: aquamarine;
position: absolute;
bottom: 0;
left: 0;
}
.box{
text-align: center;
}
.box button{
width: 200px;
height: 50px;
color: white;
font-size: 30px;
border: none;
background-color: green;
}
</style>
</head>
<body>
<div class="box">
<div class="wrapper">
<div class="boll"></div>
</div>
<button>开始</button>
</div>
<script>
var _wrapper=document.querySelector(".wrapper");
var _button=document.querySelector("button");
var _boll=document.querySelector(".boll");
_button.onclick=function(){
var speedX=6;
var speedY=10;
var id=setInterval(function(){
if(_wrapper.clientWidth-_boll.offsetLeft<=_boll.offsetWidth){
speedX*=-1;
}
_boll.style.left=(_boll.offsetLeft+speedX)+"px"
if(_boll.offsetTop<=0){
speedY*=-1;
}
_boll.style.top=(_boll.offsetTop-speedY)+"px"
if(_wrapper.clientHeight-_boll.offsetTop<=_boll.offsetHeight){
speedY*=-1;
}
if(_boll.offsetLeft<=0){
speedX*=-1;
}
},30)
}
</script>
</body>
</html>