今天來看看怎樣用面對對象來做一個躁動的小球。
首先我們先創建一個對象,他的屬性包含小球的隨機水平、縱向坐標,隨機寬、高,隨機顏色,以及創建小球的方法。
?
html:
<div id="wrap"></div>
js:
function Boll(x,y,w,h,color){// 隨機寬高var wh = randFn(5, 40);// 隨機顏色var c = 'rgb('+randFn(0, 255)+',' + randFn(0,255)+','+randFn(0, 255)+')';// 隨機x坐標 水平位置 document.body.clientWidth 網頁可見區域的寬this.x = randFn(0, document.body.clientWidth - 20);// 隨機y坐標 縱向位置 document.body.clientHeight 網頁可見區域的高this.y = randFn(0, document.body.clientHeight - 20);// 隨機顏色this.color = c;// 隨機寬高this.w = wh;this.h = wh;// 小球展示出來this.show = function(){//創建小球var bolDiv = document.createElement("div");bolDiv.style.background = this.color;bolDiv.style.left = this.x + "px";bolDiv.style.top = this.y + "px";bolDiv.style.width = this.w + "px";bolDiv.style.height = this.h + "px";// 把創建出來的小球插入到wrap里面var wrap = document.getElementById("wrap");wrap.appendChild(bolDiv);}}
?
之后把小球添加在頁面上,設定計時器來讓小隨機出現。
js:
//添加小球到頁面上var fuc = function(){// 創建小球對象var bol = new Boll();//設置小球相關數據 位置 寬高 并添加 bol.show()} //間隔性計時器 每隔一秒執行一次fuc函數 即創建小球對像并添加到頁面上window.setInterval(fuc,1000)
?
創建小球還是少不了style:
*{margin: 0px;padding: 0px;}html,body{width: 100%;height: 100%;}#wrap{width: 100%;height: 100%;background: black;position: relative;}#wrap div{position: absolute;border-radius: 50%;}
?
?