用面向?qū)ο髮懪鲎驳男∏?/h2>

創(chuàng)建小球?qū)ο蟮臉?gòu)造函數(shù)
function Boll(wh){
//隨機(jī)產(chǎn)生小球的寬高
var wh = randFn(20,50)
//設(shè)置寬高屬性和屬性值
this.width = wh;
this.height = wh;
//設(shè)置小球誕生點(diǎn)的坐標(biāo)屬性
this.top = randFn(0,document.body.offsetHeight-wh)+'px
this.left = randFn(0,document.body.offsetWidth-wh)+'px
// // 設(shè)置小球背影顏色的隨機(jī)數(shù)
// rgba(255,255,155,0.5)
this.color = 'rgba(' + randFn(0, 255) + ',' + randFn(0, 255) + ',' + randFn(0, 255) + ',' + Math.random() + ')';
//設(shè)置小球移動(dòng)速度的屬性
this.speedX = randFn(-10,10);
this.speedY = randFn(-10,10)
//設(shè)置保存小球標(biāo)簽的屬性
this.div = document.createElement('div');

}

// 原型方法:繪制小球(配置div標(biāo)簽的相關(guān)css樣式,然后把標(biāo)簽拼接進(jìn)文檔流)
//因?yàn)檫@些樣式都是一樣的,所以可以放在原型里
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é)點(diǎn)拼接進(jìn)文檔流
                wrap.appendChild(this.div);
            }
     // 原型方法:讓小球移動(dòng),且碰壁反彈
            Boll.prototype.run = function () {
                // 因?yàn)樵诙〞r(shí)器中使用的this指針是指向window對(duì)象的,要在定時(shí)器中獲取當(dāng)前操作的小球?qū)ο?,就必須在定時(shí)器外部用變量把當(dāng)前操作小球?qū)ο蟊4嫦聛?lái),在定時(shí)器內(nèi)部通過(guò)該變量獲取小球?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)用對(duì)象繪制方法,把小球繪制進(jìn)文檔
                    boll.draw();

                    // 調(diào)用小球移動(dòng)方法
                    boll.run()
                }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容