设置两个按钮,分别用于移动小球和停止小球 小球初始位置:距离文档显示区左上角(30,30) 小球直径:30 开始时,点击移动按钮,小球沿曲线向下向右移动,水平、竖直方向移动步长2,遇到文档区下边框,自动向上向前移动;遇到文档区右边框,原路返回;回到初始位置后,按同样规律移动。
时间: 2024-03-05 20:47:32 浏览: 7
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>移动小球</title>
<style>
#container {
width: 500px;
height: 500px;
border: 1px solid black;
position: relative;
}
#ball {
width: 30px;
height: 30px;
border-radius: 50%;
background-color: red;
position: absolute;
left: 30px;
top: 30px;
}
</style>
</head>
<body>
<div id="container">
<div id="ball"></div>
</div>
<button id="moveBtn">移动小球</button>
<button id="stopBtn">停止小球</button>
<script src="moveBall.js"></script>
</body>
</html>
```
JavaScript代码(moveBall.js):
```javascript
let ball = document.getElementById("ball");
let moveBtn = document.getElementById("moveBtn");
let stopBtn = document.getElementById("stopBtn");
let containerWidth = 500;
let containerHeight = 500;
let ballWidth = 30;
let ballHeight = 30;
let ballLeft = 30;
let ballTop = 30;
let moveDirection = "downRight";
let moveIntervalId;
moveBtn.onclick = function () {
moveIntervalId = setInterval(moveBall, 10);
};
stopBtn.onclick = function () {
clearInterval(moveIntervalId);
};
function moveBall() {
switch (moveDirection) {
case "downRight":
ballLeft += 2;
ballTop += 2;
if (ballLeft + ballWidth >= containerWidth) {
moveDirection = "upLeft";
ballLeft = containerWidth - ballWidth;
} else if (ballTop + ballHeight >= containerHeight) {
moveDirection = "downLeft";
ballTop = containerHeight - ballHeight;
}
break;
case "downLeft":
ballLeft -= 2;
ballTop += 2;
if (ballLeft <= 0) {
moveDirection = "upRight";
ballLeft = 0;
} else if (ballTop + ballHeight >= containerHeight) {
moveDirection = "downRight";
ballTop = containerHeight - ballHeight;
}
break;
case "upLeft":
ballLeft -= 2;
ballTop -= 2;
if (ballLeft <= 0) {
moveDirection = "downRight";
ballLeft = 0;
} else if (ballTop <= 0) {
moveDirection = "upRight";
ballTop = 0;
}
break;
case "upRight":
ballLeft += 2;
ballTop -= 2;
if (ballLeft + ballWidth >= containerWidth) {
moveDirection = "downLeft";
ballLeft = containerWidth - ballWidth;
} else if (ballTop <= 0) {
moveDirection = "upLeft";
ballTop = 0;
}
break;
}
ball.style.left = ballLeft + "px";
ball.style.top = ballTop + "px";
}
```