在HTML里建一個(gè)div屏轰,id="wrap"
css樣式
*{
margin:0;
padding:0;
}
body,html{
height:100%;
}
#wrap{
height:100%;
background-color:black;
position:relative;
overflow:hidden;
}
.ball{
border-radius:50%;
position:absolute;
}
js代碼
//工具函數(shù),產(chǎn)生[min,max)范圍內(nèi)的隨機(jī)數(shù)
functionrandFn(min,max){
returnparseInt(Math.random()*(max-min)+min);
}
//創(chuàng)建構(gòu)造函數(shù),由構(gòu)造函數(shù)獲取小球?qū)ο?/p>
functionBoll(){
//小球的尺寸:隨機(jī)數(shù)
varwh = randFn(20,50);
this.width= wh; //width不是css中的,只是容器
this.height= wh;
//小球初始坐標(biāo)點(diǎn)
this.left= randFn(0,document.body.offsetWidth-wh);
this.top= randFn(0,document.body.offsetHeight-wh);
//小球顏色:隨機(jī)
this.color= "rgba(" + randFn(0,256) + "," + randFn(0,256) +"," + randFn(0,256) + "," + Math.random() + ")";
//小球運(yùn)動(dòng)速度:隨機(jī)
this.speedX= randFn(-10,10); //有正值,有負(fù)值一開(kāi)始可以往左往右
this.speedY= randFn(-10,10);
//開(kāi)辟屬性,保存創(chuàng)建出來(lái)的DOM節(jié)點(diǎn)
this.div= document.createElement("div");
}
//添加繪制小球的方法
Ball.prototype.draw= function(){
this.div.className= "ball";
this.div.style.width= this.width+"px";
this.div.style.height= this.height+"px";
this.div.style.left= this.left+"px";
this.div.style.top= this.top+"px";
this.div.style.backgroundColor= this.color;
//把標(biāo)簽拼接進(jìn)文檔流
varwrap = document.querySelector("#wrap");
wrap.appendChild(this.div);
}
Boll.prototype.run= function(){
varself = this;
setInterval(function(){
//this指向window
//判斷邊界情況
if(self.div.offsetLeft+ self.div.offsetWidth>=document.body.offsetWidth ||self.div.offsetLeft<0){
self.speedX*=-1;
}
if(self.div.offsetTop+self.div.offsetHeight>=document.body.offsetHeight|| self.div.offsetTop<0){
self.speedY*=-1;
}
self.div.style.left= self.div.offsetLeft+self.speedX+"px";
self.div.style.top= self.div.offsetTop+self.speedY+"px";
},10)
}
window.onload= function(){
for(vari=0;i<100;i++){
varball = new Ball();
ball.draw();
ball.run();
}
}