实现小球在页面规定的区域运动,需要用到JavaScript语言实现动态效果。
具体的步骤和示例说明如下:
<div id="ball" style="position:absolute; width:20px; height:20px; border-radius:50%; background-color:red;"></div>
var leftBound = 0, rightBound = 600, topBound = 0, bottomBound = 400;
var ball = document.getElementById('ball');
var vx = 5, vy = 2;
function moveBall() {
var x = parseInt(ball.style.left);
var y = parseInt(ball.style.top);
if (x + vx > rightBound || x + vx < leftBound) {
vx = -vx;
}
if (y + vy > bottomBound || y + vy < topBound) {
vy = -vy;
}
x += vx;
y += vy;
ball.style.left = x + "px";
ball.style.top = y + "px";
}
setInterval(moveBall, 30);
示例1:实现小球随机运动
<!DOCTYPE html>
<html>
<head>
<title>小球随机运动</title>
<meta charset="utf-8">
<style type="text/css">
#ball {
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: red;
}
</style>
</head>
<body>
<div id="ball"></div>
<script type="text/javascript">
var leftBound = 0, rightBound = 600, topBound = 0, bottomBound = 400;
var ball = document.getElementById('ball');
var vx = getRandomNumber(-10, 10), vy = getRandomNumber(-10, 10);
function moveBall() {
var x = parseInt(ball.style.left);
var y = parseInt(ball.style.top);
if (x + vx > rightBound || x + vx < leftBound) {
vx = -vx;
}
if (y + vy > bottomBound || y + vy < topBound) {
vy = -vy;
}
x += vx;
y += vy;
ball.style.left = x + "px";
ball.style.top = y + "px";
}
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
setInterval(moveBall, 30);
</script>
</body>
</html>
示例2:实现多个小球同时运动
<!DOCTYPE html>
<html>
<head>
<title>多个小球同时运动</title>
<meta charset="utf-8">
<style type="text/css">
.ball {
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: red;
}
</style>
</head>
<body>
<div class="ball"></div>
<div class="ball"></div>
<div class="ball"></div>
<div class="ball"></div>
<div class="ball"></div>
<script type="text/javascript">
var leftBound = 0, rightBound = 600, topBound = 0, bottomBound = 400;
var balls = document.getElementsByClassName('ball');
for (var i = 0; i < balls.length; i++) {
initBall(balls[i]);
}
function initBall(ball) {
ball.style.left = getRandomNumber(leftBound, rightBound - parseInt(ball.style.width)) + "px";
ball.style.top = getRandomNumber(topBound, bottomBound - parseInt(ball.style.height)) + "px";
ball.vx = getRandomNumber(-10, 10);
ball.vy = getRandomNumber(-10, 10);
}
function moveBall() {
for (var i = 0; i < balls.length; i++) {
var ball = balls[i];
var x = parseInt(ball.style.left);
var y = parseInt(ball.style.top);
if (x + ball.vx > rightBound || x + ball.vx < leftBound) {
ball.vx = -ball.vx;
}
if (y + ball.vy > bottomBound || y + ball.vy < topBound) {
ball.vy = -ball.vy;
}
x += ball.vx;
y += ball.vy;
ball.style.left = x + "px";
ball.style.top = y + "px";
}
}
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
setInterval(moveBall, 30);
</script>
</body>
</html>
本文链接:http://task.lmcjl.com/news/8752.html