通过改变小球的left和top值来改变小球的移动 小球与小球之间的碰撞,要判断小球在被撞小球的哪个方向,从而判断小球该向哪个方向移动,同样的改变小球的坐标值,来实现小球的反弹
1. 先实现一个小球在固定容器内随机起点随机速度移动
<!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>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>
// s = v * t
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 () {
// 每一次时间间隔,让dBall进行一次单位移动
// dBall的新位置 = dBall的当前位置 + 速度
// offsetLeft 距离定位父级的左侧偏移量 (只读)
// offsetTop 距离定位父级的顶部偏移量 (只读)
var l = dBall.offsetLeft + vx;
var t = dBall.offsetTop + vy;
// 边界处理
if (t > 260) {
t = 260;
vy = -vy;
}
else if (t < 0) {
t = 0;
vy = -vy;
}
if (l > 760) {
l = 760
vx = -vx;
}
else if (l < 0) {
l = 0;
vx = -vx;
}
dBall.style.left = l + 'px';
dBall.style.top = t + 'px';
}, 30)
// 随机函数
function rand(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
</script>
</html>
实现效果图如下
2.实现多个小球在一固定容器内随机起点随机速度移动
代码段如下
<!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>case04</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-c