效果圖:
HTML
<div class='box'>
<div class='ball'></div>
</div>
style:
.box{
width:300px;
height:400px;
background-color:green;
opacity:0.5;
margin:auto;
position:relative;
}
.ball{
width:20px;
height:20px;
border-radius:50%;
background-color:yellow;
position:absolute;
}
javascript:
window.onload = function() {
var ball = document.getElementsByClassName('ball')[0];
var box = document.getElementsByClassName('box')[0];
function ballMove() {
var speed = 2;//定義總體速度
//隨機設置小球的初始位置
var ballX = (box.offsetWidth - ball.offsetWidth) * Math.random();
var ballY = (box.offsetHeight - ball.offsetHeight) * Math.random();
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
//隨機設置小球在x和y方向的速度
var theta = 2 * Math.PI * Math.random();
var speedX = speed * Math.cos(theta);
var speedY = speed * Math.sin(theta);
setInterval(function() {
//隨機控制小球在X和Y方向上的位置
ballX += speedX;
ballY += speedY;
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
//如果小球彈出邊框時改變它的方向
if(ballX + ball.offsetWidth >= box.offsetWidth || ballX <= 0) {
speedX = -speedX;
}
if(ballY + ball.offsetHeight >= box.offsetHeight || ballY <= 0) {
speedY = -speedY;
}
},10)
}
ballMove();
}