一、让小球在一个范围内直线运动,遇到边界则返回
代码:
<!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>case1</title>
<style>
* {
margin: 0;
padding: 0;
}
.wrap {
width: 800px;
height: 300px;
position: relative;
margin: 0 auto;
background-color:rgba(0,0,0,.5);
border: 1px solid black;
}
.ball {
width: 40px;
height: 40px;
background-color:tomato;
border-radius: 50%;
position: absolute;
top: 130px;
left: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="ball"></div>
</div>
</body>
<script>
// s=v*t
var dball = document.querySelector(".ball");
var timer = null;
var v = 5;
// 开启定时器
timer = setInterval(function () {
// 每一次时间间隔,让dball进行一次单位移动
// dball的新位置=dball的当前位置+速度
// offsetLeft 距离定位父级的左侧偏移量(只读)
// offsetTop距离定位父级的顶部偏移量(只读)
// 边界处理
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';
}, 30)
</script>
</html>
二、改进:给小球添加一个向上的运动
代码:
<!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>case2</title>
<style>
* {
margin: 0;
padding: 0;
}
.wrap {
width: 800px;
height: 300px;
position: relative;
margin: 0 auto;
background-color:rgba(0,0,0,.5);
border: 1px solid black;
}
.ball {
width: 40px;
height: 40px;
background-color: yellowgreen;
border-radius: 50%;
position: absolute;
top: 130px;
left: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="ball"></div>
</div>
</body>
<script>
// s=v*t
var dball = document.querySelector(".ball");
var timer = null;
var vx = 5;
var vy = 5;
// 开启定时器
timer = setInterval(function () {
// 每一次时间间隔,让dball进行一次单位移动
// dball的新位置=dball的当前位置+速度
// offsetLeft 距离定位父级的左侧偏移量(只读)
// offsetTop距离定位父级的顶部偏移量(只读)
// 边界处理
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';
}, 30)
</script>
</html>
三、改进:让小球在任一起点开始运动
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=dev