case01_边界碰撞:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>case01</title>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
width: 800px;
height: 300px;
position: relative;
margin: 0 auto;
border: 1px solid black;
}
.ball{
width: 40px;
height: 40px;
background-color: pink;
border-radius: 50%;
position: absolute;
top: 130px;
left: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="ball"></div>
</div>
</body>
<script>
var dBall = document.querySelector(".ball");
var timer = null;
var v = 5;
timer = setInterval(function() {
var l = dBall.offsetLeft + v;
if(l > 760){
l = 760;
v = -5;
}else if (l < 0) {
l = 0;
v = 5;
}
dBall.style.left = l + 'px';
},1000/24);
</script>
</html>

case02_随意运动:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>case02</title>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
width: 800px;
height: 300px;
position: relative;
margin: 0 auto;
border: 1px solid black;
}
.ball{
width: 40px;
height: 40px;
background-color: pink;
border-radius: 50%;
position: absolute;
top: 130px;
left: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="ball"></div>
</div>
</body>
<script>
var dBall = document.querySelector(".ball");
var timer = null;
var vx = 5;
var vy = 5;
timer = setInterval(function() {
var l = dBall.offsetLeft + vx;
var t = dBall.offsetTop + vy;
if(l > 760){
l = 760;
vx = -5;
}else if (l < 0) {
l = 0;
vx = 5;
}
if(t > 260){
t = 260; vy = -5;
}else if(t < 0){
t = 0; vy = 5;
}
dBall.style.left = l + 'px';
dBall.style.top = t + 'px';
},1000/24);
</script>
</html>

case03_随机起点、速度:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>case03</title>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
width: 800px;
height: 300px;
position: relative;
margin: 0 auto;
border: 1px solid black;
}
.ball{
width: 40px;
height: 40px;
background-color: pink;
border-radius: 50%;
position: absolute;
top: 130px;
left: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="ball"></div>
</div>
</body>
<script>
var dBall = document.querySelector(".ball");
var timer = null;
var vx = 0;
var vy = 0;
(function() {
vx = Math.random() > 0.5 ? rand(3,10) : -rand(3,10);
vy = Math.random() > 0.5 ? rand(3,10) : -rand(3,10);
dBall.style.left = rand(0,760) + 'px';
dBall.style.top = rand(0,260) + 'px;';
})()
timer = setInterval(function() {
var l = dBall.offsetLeft + vx;
var t = dBall.offsetTop + vy;
if(l > 760){
l = 760;
vx = -vx;
}else if (l < 0) {
l = 0;
vx = -vx;
}
if(t > 260){
t = 260; vy = -vy;
}else if(t < 0){
t = 0; vy = -vy;
}
dBall.style.left = l + 'px';
dBall.style.top = t + 'px';
},1000/24);
function rand(min,max){
return Math.round(Math.random() * (max-min) + min);
}
</script>
</html>