分析:
搭建10 * 10 的小方块
<script type="text/javascript" >
var body = document.getElementsByTagName('body')[0]; //返回数组[0]
var wrap = document.createElement('div');
wrap.style.width = '500px';
wrap.style.height = '500px';
wrap.style.border = '1px solid gray';
wrap.style.margin = '0 auto';
wrap.style.position = 'relative';
var arr = []; //用于存放每个div小方格
for(var i = 0; i < 10; i++) {
for( var j = 0; j < 10; j++) {
var light = document.createElement('div'); //创建小方格
light.style.width = '50px';
light.style.height = '50px';
light.style.background = 'black';
light.style.border = '1px solid gray';
light.style.position = 'absolute';
light.style.left = i * 10 + '%';
light.style.top = j * 10 + '%';
light.index = arr.length;
arr.push(light);// 将div 添加到数组中
light.onclick = function() { //添加点击事件
var currentLight = event.target; //获取当前的灯
if(currentLight.style.background == 'black') {
currentLight.style.background = 'blue';
} else {
currentLight.style.background = 'black';
}
if (currentLight.index >= 10) {
var top = arr[currentLight.index - 10];
top.style.background = (top.style.background == 'black') ? 'blue' : 'black';
}
if (currentLight.index + 10 < arr.length) {
var bottom = arr[currentLight.index + 10];
bottom.style.background = (bottom.style.background == 'black') ? 'blue' : 'black';
}
if(currentLight.index % 10 != 0 ){
var left = arr[currentLight.index - 1];
left.style.background = (left.style.background== 'black') ? 'blue' : 'black';
}
if(currentLight.index % 10 < 9) {
var right = arr[currentLight.index + 1];
right.style.background = (right.style.background == 'black') ? 'blue' : 'black';
}
}
wrap.appendChild(light);
}
}
body.appendChild(wrap);
</script>