我如何为单元格指定3种颜色,并在每次点击时更改它们?假设我有一个10x10的表,默认颜色是白色,在第一次单击它变为黑色的单元格时,第二次变为灰色,第三次再变为白色,并且对于每种颜色,单元格也会得到一个值,如:
白色:0
黑色:1
灰色:2。
我想制作一个益智游戏(Griddler),如果拼图正确解决,每个单元格必须是黑色和灰色。
答案 0 :(得分:1)
在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];
}
}
(请注意,在浏览器中,如果您需要支持,请在旧版IE中使用addEventListener
并使用attachEvent
填充内容的事件监听器