<!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>
* {
margin: 0;
padding: 0;
}
header {
width: 600px;
height: 500px;
border: 10px dashed red;
position: relative;
}
div {
width: 100px;
height: 100px;
background-color: blue;
border-radius: 50%;
position: absolute;
}
button {
font-size: 30px;
padding: 6px 10px;
}
</style>
</head>
<body>
<header>
<div></div>
</header>
<button>开始</button>
<button disabled>暂停</button>
</body>
</html>
<script>
var header = document.querySelector("header");
var div = document.querySelector("div");
var timer = null;
// 初始值
var x = 0;
var y = 0;
// 方向
var addX = true;
var addY = true;
// 临界值 盒子宽度 - 球的直径
var xMax = header.scrollWidth - div.offsetWidth;
var yMax = header.scrollHeight - div.offsetHeight;
document.querySelector("button").onclick = function () {
// 暂停放开
document.querySelectorAll("button")[1].disabled = false;
this.disabled = true;
timer = setInterval(function () {
// div.style.left = num + "px"
// div.style.top = num + "px"
// 规定一个初始速度还有方向
if (addX) {
x++;
// 判断警戒值
if (x >= xMax) {
// 此时水平方向达到最大值,改更改方向
addX = false;
} else {
// 水平方向赋值
div.style.left = x + "px";
}
} else {
// 更改方向
x--;
// 判断警戒值
if (x <= 0) {
// 此时水平方向达到最大值,改更改方向
addX = true;
} else {
// 水平方向赋值
div.style.left = x + "px";
}
}
// 垂直方向
if (addY) {
y+=10;
if (y >= yMax) {
addY = false;
} else {
div.style.top = y + "px";
}
} else {
y--;
if (y <= 0) {
addY = true;
} else {
div.style.top = y + "px";
}
}
}, 1);
};
document.querySelectorAll("button")[1].onclick = function () {
document.querySelector("button").disabled = false;
this.disabled = true;
clearInterval(timer);
};
</script>
小球触壁反弹
最新推荐文章于 2023-10-14 20:25:00 发布