效果图:
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