js case (ball movement)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/*外部控制样式*/
.wrapper {
width: 300px;
margin: 0 auto;
}
/*运动容器*/
.container {
width: 500px;
height: 300px;
border: 5px solid black;
position: relative;
}
/*开始按钮*/
button {
width: 80px;
height: 30px;
border: none;
background-color: green;
border-radius: 5px;
color: #fff;
margin-top: 5px;
}
/*小球样式*/
.ball {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
position: absolute;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="ball"></div>
</div>
<button>开始</button>
</div>
</body>
<script>
var _container=document.querySelector(".container");//获取容器节点
var _ball=document.querySelector(".ball");//获取小球节点
var _btn=document.querySelector("button");//获取按钮节点
//按钮点击事件
_btn.onclick=function(){
var speedX=6;//水平方向速度
var speedY=6;//垂直方向速度
//设置计时器(动起来的关键)
var id=setInterval(function(){
//小球水平方向位移
_ball.style.left=_ball.offsetLeft+speedX+"px";
//小球垂直方向位移
_ball.style.top=_ball.offsetTop-speedY+"px";
//到小球碰到最右侧边框时改变水平运动方向
if(_container.clientWidth-_ball.offsetLeft<=_ball.clientWidth){
speedX*=-1;
}
//到小球碰到最上侧边框时改变垂直运动方向
if(_ball.offsetTop<=0){
speedY*=-1;
}
//到小球碰到最左侧边框时改变水平运动方向
if(_ball.offsetLeft<=0){
speedX*=-1;
}
//到小球碰到最下侧边框时改变垂直运动方向
if(_container.clientHeight-_ball.offsetTop<=_ball.clientHeight){
speedY*=-1;
}
//每隔100毫秒变化一次
},100)
}
</script>
</html>
Effect picture:
initial state:
running: