游戲規(guī)則:在變化數(shù)量的顏色塊里找出一個不同顏色的塊點擊
這里使用了JS中的構(gòu)造函數(shù)來創(chuàng)建元素

<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>找不同色塊的游戲(構(gòu)造函數(shù))</title></head><style> *{ margin: 0; padding: 0; } #box{ width: 600px; height: 600px; margin: auto; margin-top: 100px; } #score{ width: 180px; height: 50px; line-height: 150%; font-size: 2em; position: absolute; top: 30px; left: 35%; } .creat{ float: left; border-radius: 100%; }</style><body> <div id="score">關(guān)卡:1</div> <div id="box"></div> <script> var n=1;//關(guān)卡值 var Create=new creat(3);//定義構(gòu)造函數(shù)對象,傳入一個參數(shù)(開始時的布局3x3) Create.go();//調(diào)用構(gòu)造函數(shù)里面的函數(shù)屬性 function creat(event){//定義構(gòu)造函數(shù)creat var obox=document.getElementById("box"); this.className="creat";//設(shè)置className this._creat=null;//事先創(chuàng)建出一個屬性_creat用于指向一個對象 this.go=function(){//創(chuàng)建顏色塊的方法函數(shù) var colorNum1=Math.floor(Math.random()*253)+1;//隨機數(shù)取一個值范圍是(1~254)防止白色塊出現(xiàn) var colorNum2=Math.floor(Math.random()*253)+1; var colorNum3=Math.floor(Math.random()*253)+1; this.color="rgb("+colorNum1+","+colorNum2+","+colorNum3+")";//定義rgb顏色屬性 this.diffOpacity=0.7;//用于改變其中一個顏色快的顏色(這里可以自定義改變透明度) for(var i=0;i<event*event;i++){//創(chuàng)建循環(huán)循環(huán)event*2次,每當點擊顏色塊后event變化 this._creat=document.createElement("div");//動態(tài)創(chuàng)建一個div賦給this._creat屬性 this._creat.style.width=Math.floor(600/event)+"px";//設(shè)置div的寬,高,顏色和className this._creat.style.height=Math.floor(600/event)+"px"; this._creat.style.backgroundColor=this.color; this._creat.className=this.className;//在樣式中給div左浮動 obox.appendChild(this._creat);//作為孩子添加到obox中 } var odiv=document.getElementsByClassName("creat");//獲取一下創(chuàng)建好的div var numRandom=parseInt(Math.random()*odiv.length);//隨機取到其中一個改變其透明度值 odiv[numRandom].style.opacity=this.diffOpacity; odiv[numRandom].onclick=function(){ /*給取到的div綁定事件,當點擊時先清空obox中元素即上一關(guān)卡的div *獲取score改變n的值 *改變event的值,可以自定義難度 *再調(diào)用一下調(diào)用構(gòu)造函數(shù)里面的go函數(shù)屬性,創(chuàng)建一組新的元素 */ var oScore=document.getElementById("score"); n++; oScore.innerHTML="關(guān)卡:"+n+""; obox.innerHTML=""; event++; Create.go(); } } } </script></body></html>以上所述是小編給大家介紹的Javascript實現(xiàn)找不同色塊的游戲,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答