单个小球运动的代码如下
多个小球运动的示例代码下载地址:https://download.csdn.net/download/qq_36330464/89073445
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>小球撞击</title>
<style>
.ball {
display: block;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: green;
position: absolute;
}
</style>
</head>
<body>
<div>
<span class="ball"></span>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
// 定义小球的初始坐标
var x0 = 0
var y0 = 0
// 定义小球当前的坐标
var x = 0
var y = 0
// 1/-1改变小球移动的方向
var directionX = 1
var directionY = 1
// 获取小球 DOM 元素
var ball = $('.ball')
function move(speed) {
// offset() 返回的是所选元素相对于当前文档的坐标
var vTop = ball.offset().top
var vLeft = ball.offset().left
// console.log('小球当前的坐标为:(' + vLeft + ',' + vTop + ')')
x = x0 + vLeft + directionX * speed
y = y0 + vTop + directionY * speed
if (ball.offset().top + 50 >= $(document).height()) {
directionY = -1
} else if (y <= 0) {
directionY = 1
}
if (ball.offset().left + 50 >= $(document).width()) {
directionX = -1
} else if (x <= 0) {
directionX = 1
}
ball.css('top', y + 'px')
ball.css('left', x + 'px')
}
// 每隔 1 毫秒执行一次 Move 函数,更新小球的位置
setInterval(function () {
move(1)
}, 1)
</script>
</body>
</html>