ruby_xc通过本文主要向大家介绍了javascript等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
在指定div中运动
html:
<div id="box">
<div id="ball"></div>
</div>
css:
#ball{
width:80px;
height:80px;
background: skyblue;
border-radius: 50%;
position:relative;
}
#box{
width: 500px;
height: 500px;
position: absolute;
top: 10%;
left: 20%;
border: 2px solid #337733;
}
js:
var ball = document.getElementById('ball'),
leftDis = 5;
topDis = 5;
leftMax = document.getElementById("box").clientWidth-ball.clientWidth;
topMax = document.getElementById("box").clientHeight-ball.clientHeight;
var box = document.getElementById("box");
ball.style.top = Math.random()*(box.offsetTop,box.offsetHeight+box.offsetTop)+'px';
ball.style.left = Math.random()*(box.offsetLeft,box.offsetWidth+box.offsetLeft)+'px';
setInterval(function(){
var Left = ball.offsetLeft+leftDis,
Top = ball.offsetTop+topDis;
if(Left>=leftMax){
Left = leftMax;
leftDis = -leftDis;
ballColor(ball);
}else if(Left<=0){
Left = 0;
leftDis = -leftDis;
ballColor(ball);
};
if(Top>=topMax){
Top = topMax;
topDis = -topDis;
ballColor(ball);
}else if(Top<=0){
Top = 0;
topDis = -topDis;
ballColor(ball);
};
ball.style.left = Left+'px';
ball.style.top = Top+'px';
},30);
function ballColor(obj){
var r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
obj.style.backgroundColor = 'rgb('+r+','+g+','+b+')';
}