<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body{
background-color:#000;
}
</style>
</head>
<body>
<script type="text/javascript">
//设置球体的信息:颜色,大小,移动速度,位置
//利用构造函数的方法 创建小球
function Ball(color,size,posX,posY,speedX,speedY){
this.carrier=document.createElement("div");
this.color=color;
this.size=size;
this.posX=posX;
this.posY=posY;
this.speedX=speedX;
this.speedY=speedY;
//给载体添加样式
this.init=function(){
this.carrier.style.background=this.color;
this.carrier.style.width=this.size+"px";
this.carrier.style.height=this.size+"px";
this.carrier.style.borderRadius="50%";
this.carrier.style.position="absolute";
this.carrier.style.left=this.posX+"px";
this.carrier.style.top=this.posY+"px";
//将设置好的小球样式添加到body上
document.body.appendChild(this.carrier);
};
//
this.move=function(){
//将this指针赋值给变量balls上
var balls=this;
//创建定时器 判断小球距离上下左右方向运动
setInterval(function(){
//offsetLeft的值得意思是:元素左边的值距离它父级的值(需要给元素做地位才可使用),offsetWidth的值得意思是:元素本身的宽度
if (balls.carrier.offsetLeft < 0 || balls.carrier.offsetLeft + balls.carrier.offsetWidth + balls.speedX > w()) {
balls.speedX = -balls.speedX;
}
//offsetTop的值得意思是:元素上边的值距离它父级的值,offsetHeight的值得意思是:元素本身的高度
if (balls.carrier.offsetTop < 0 || balls.carrier.offsetTop + balls.carrier.offsetHeight + balls.speedY > h()) {
balls.speedY = -balls.speedY;
}
//获取小球左边样式的值
balls.carrier.style.left = balls.carrier.offsetLeft + balls.speedX + "px";
//上面的值
balls.carrier.style.top = balls.carrier.offsetTop + balls.speedY + "px";
},50);
}
}
//通过for循环 赋值小球的样式 因为所有的样式都是随机产生的 所以用到Math.random()*((m+1-n)-n);
for(var i=0;i<50;i++){
var size=parseInt(Math.random()*11+30);
var posX=parseInt(Math.random()*(w()-size));
var posY=parseInt(Math.random()*(h()-size));
var speedX=parseInt(Math.random()*5+6*(parseInt(Math.random()*2)==0?1:-1));
var speedY=parseInt(Math.random()*5+6*(parseInt(Math.random()*2)==0?1:-1));
//构造函数传参数 必须通过new的方法
var a=new Ball(col(),size,posX,posY,speedX,speedY);
//调用初始化
a.move();
a.init();
}
//获取页面的宽高
function w(){
return document.documentElement.clientWidth||document.body.clientWidth;
}function h(){
return document.documentElement.clientHeight||document.body.clientHeight;
}
//随机创造颜色
function col(){
var str="1234567890abcdef";
var str2="#";
for(var i=0;i<6;i++){
//随机创造颜色
var index=Math.floor(Math.random()*str.length);
str2+=str.charAt(index);
}
return str2;
}
</script>
</body>
</html>
![]()