創(chuàng)建小球?qū)ο蟮臉?gòu)造函數(shù)
function Boll(wh){
//隨機產(chǎn)生小球的寬高
var wh = randFn(20,50)
//設(shè)置寬高屬性和屬性值
this.width = wh;
this.height = wh;
//設(shè)置小球誕生點的坐標屬性
this.top = randFn(0,document.body.offsetHeight-wh)+'px
this.left = randFn(0,document.body.offsetWidth-wh)+'px
// // 設(shè)置小球背影顏色的隨機數(shù)
// rgba(255,255,155,0.5)
this.color = 'rgba(' + randFn(0, 255) + ',' + randFn(0, 255) + ',' + randFn(0, 255) + ',' + Math.random() + ')';
//設(shè)置小球移動速度的屬性
this.speedX = randFn(-10,10);
this.speedY = randFn(-10,10)
//設(shè)置保存小球標簽的屬性
this.div = document.createElement('div');
}
// 原型方法:繪制小球(配置div標簽的相關(guān)css樣式,然后把標簽拼接進文檔流)
//因為這些樣式都是一樣的,所以可以放在原型里
Boll.prototype.draw = function () {
this.div.className = 'boll';
this.div.style.width = this.width + 'px';
this.div.style.height = this.height + 'px';
this.div.style.top = this.top;
this.div.style.left = this.left;
this.div.style.backgroundColor = this.color;
// 把配置好的節(jié)點拼接進文檔流
wrap.appendChild(this.div);
}
// 原型方法:讓小球移動,且碰壁反彈
Boll.prototype.run = function () {
// 因為在定時器中使用的this指針是指向window對象的,要在定時器中獲取當前操作的小球?qū)ο?,就必須在定時器外部用變量把當前操作小球?qū)ο蟊4嫦聛?,在定時器內(nèi)部通過該變量獲取小球?qū)ο? var self = this;
setInterval(function () {
var tag = self.div;
if (tag.offsetLeft + tag.offsetWidth >= wrap.offsetWidth || tag.offsetLeft < 0) {
self.speedX *= -1;
}
if (tag.offsetTop + tag.offsetHeight >= wrap.offsetHeight || tag.offsetTop < 0) {
self.speedY *= -1;
}
tag.style.left = tag.offsetLeft + self.speedX + 'px';
tag.style.top = tag.offsetTop + self.speedY + 'px';
},30)
}
for (var i = 0; i < 100; i++) {
// 創(chuàng)建小球?qū)ο?br>
var boll = new Boll();
// 調(diào)用對象繪制方法,把小球繪制進文檔
boll.draw();
// 調(diào)用小球移動方法
boll.run()
}