JavaScript实例 躁动的小球
<!doctype html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
html,body{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: #000;
overflow: hidden;
position: absolute;
}
div{
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<script type="text/javascript">
var d1=document.getElementById('d1')
function Ball(obj){
this._init(obj);
}
Ball.prototype={
// 初始化
_init:function(obj){
// 获取父节点
this.parentnode=obj.parentNode;this.div=document.createElement('div');
this.r=ranDom(10,70);
this.x=ranDom(0,1200);
this.y=ranDom(0,500);
// 小球背景颜色的设置 this.color=`rgba(${ranDom(0,255)},${ranDom(0,255)},${ranDom(0,255)},${Math.random()*0.6+0.4})`; //设置透明度
this.speedX=ranDom(-10,20);
this.speedY=ranDom(-10,20);
},
// 显示小球show:function(){
var div=this.div;
div.style.width=this.r*2+"px"; //注意这些地方的px一定要加上去 因为CSS的样式为字符串类型 所以要+上“px”;
div.style.height=this.r*2+"px";
div.style.background=this.color;
div.style.left=this.x+"px";
div.style.top=this.y+"px";
this.parentnode.appendChild(div);
},
// 设置移动roll:function(){
var div=this.div;
var i=1;
var j=1;
var speedX=this.speedX;
var speedY=this.speedY;
var maxLeft=this.parentnode.offsetWidth-div.offsetWidth;
var maxTop=this.parentnode.offsetHeight-div.offsetHeight;
// 定时器setTimeout(function loop(){
if(div.offsetLeft>maxLeft|| div.offsetLeft<0){
i*=-1;
}
if(div.offsetTop>maxTop|| div.offsetTop<0){
j*=-1;
}
div.style.left=div.offsetLeft+i*speedX+"px";
div.style.top=div.offsetTop+j*speedY+"px";
setTimeout(loop,20);
},20);
},
}
// 设置小球的个数for(var i=0;i<20;i++){
var b2= new Ball({parentNode:document.body});
b2.show();
b2.roll();
}
// 随机数function ranDom(small,big){
return parseInt(Math.random()*(big-small+1)+small);
}
</script>
</body>
</html>