2013-04-01 100 views
0

如何將3種顏色分配給單元格,並在每次單擊時更改它們?比方說,我有一個10x10的表,默認的顏色是白色的,第一次點擊它變成黑色的單元格,第二次變成灰色,第三次變成白色,對於每種顏色,單元格也獲得一個值,如:使用JavaScript更改鼠標點擊時表格單元格的顏色

白:0
黑色:1
灰色:2

我想打一個益智遊戲(Griddler準確),如果讓人不解的是每一個細胞都必須是黑色和灰色的正確解決。

回答

1

Here is a working fiddle

window.onload(或DOM準備好了,無論你想):

var colors = ["white","black","gray"]//array of colors 
var reverseRef = {"white":0,"black":1,"gray":2}; 

var cells = document.getElementsByClassName("block");//block is a class name you should give your blocks 

for(var i=0;i<cells.length;i++){//attach an event to all blocks 
    cells[i].onclick = function(){//when you click them 
     //change the background color 
     //(reverseRef[this.styles.backgroundColor]+1)%3 means get the number value for the color, increase it by one, and modulus it by 3 (which means you only get values between 0 and 2 
     this.style.backgroundColor=colors[(reverseRef[this.style.backgroundColor]+1)%3]; 
    } 
} 

(注意,在瀏覽器的onclick應使用addEventListener和舊有attachEvent勻場事件偵聽器IE如果你需要支持它)

相關問題