First create a small box and a small ball
<div id="box">
<div id="ball"></div>
</div>
Then set the style (size, color, positioning)
<style>
#box {
width: 800px;
height: 500px;
position: absolute; //定位 使其先对浏览器 水平垂直都居中
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
border: 2px #555 solid; //边框
}
#ball {
width: 80px;
height: 80px;
border-radius: 50%; // 圆角 让div变成球型
background-color: crimson;
position: absolute;
}
</style>
Then use js to let the ball bounce infinitely (absolute positioning)
<script>
var oBall = document.getElementById("ball"); //获取小球
var speedx = 1; //水平移动的幅度
var speedy = 1; //垂直移动的幅度
var x = 1, y = 1;
setInterval(() => {
//计时器
x += speedx; //使小球一次移动一个speed
if (x > 720 || x < 0) {
speedx = speedx * -1; //当小球碰壁 speed变为-1 小球就会往回走
}
y += speedy;
if (y > 420 || y < 0) {
speedy = speedy * -1;
}
oBall.style.left = `${
x}px`; // 设置小球绝对定位的 left 和 top 来使其移动
oBall.style.top = `${
y}px`;
}, 2) //小球的绝对定位 每2毫秒改变一次
</script>
Full code:
<!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>
#box {
width: 800px;
height: 500px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
border: 2px #555 solid;
}
#ball {
width: 80px;
height: 80px;
border-radius: 50%;
background-color: rgb(4, 175, 243);
position: absolute;
}
</style>
</head>
<body>
<div id="box">
<div id="ball"></div>
</div>
<script>
var oBall = document.getElementById("ball");
var speedx = 1;
var speedy = 1;
var x = 1, y = 1;
setInterval(() => {
x += speedx;
if (x > 720 || x < 0) {
speedx = speedx * -1;
}
y += speedy;
if (y > 420 || y < 0) {
speedy = speedy * -1;
}
oBall.style.left = `${
x}px`;
oBall.style.top = `${
y}px`;
}, 0.01)
</script>
</body>
</html>
Renderings: