一个翻翻的小游戏。HTML式。

javascript 复制代码
<!DOCTYPE html>
<html>
<head>
    <style>
    	#grid{
    		width:316px;
    		height: 316px;
    		 background-color: #00BFFF;    		
    	}
        .cell {
            width: 60px;
            height: 60px;
            border: 1px solid black;
            float: left;           
        }
        .red {
            background-color: red;
        }
        .black {
            background-color: black;
        }
    </style>
</head>
<body>
    <div id="grid"></div>
    <script>
        var grid = [];
        var size = 5;
        var gridElement = document.getElementById('grid');

        for (var i = 0; i < size; i++) {
            var row = [];
            for (var j = 0; j < size; j++) {
                var cell = document.createElement('div');
                cell.className = 'cell red';
                cell.onclick = (function(i, j) {
                    return function() {
                        toggleColor(i, j);
                    }
                })(i, j);
                gridElement.appendChild(cell);
                row.push(cell);
            }
            grid.push(row);
        }

        grid[2][2].className = 'cell black';

        function toggleColor(i, j) {
            var directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
            for (var k = 0; k < directions.length; k++) {
                var ni = i + directions[k][0];
                var nj = j + directions[k][1];
                if (ni >= 0 && ni < size && nj >= 0 && nj < size) {
                    var cell = grid[ni][nj];
                    cell.className = cell.className === 'cell red' ? 'cell black' : 'cell red';
                }
            }
        }
    </script>
</body>
</html>
相关推荐
向量引擎1 小时前
从零起步,如何打造专属向量引擎 API 中转工作流?
java·服务器·前端
丷丩1 小时前
MapLibre GL JS第27课:添加COG栅格源
javascript·map·mapbox·maplibre gl js
IT_陈寒1 小时前
Vue这个动态响应坑把我整不会了
前端·人工智能·后端
bestlanzi1 小时前
使用nvm管理node环境
前端·vue.js·npm
SomeOtherTime2 小时前
Geojson相关(AI回答)
java·前端·python
不好听6132 小时前
JavaScript 到底是怎么运行的?从编译阶段到执行上下文全面解析
javascript
丷丩3 小时前
MapLibre GL JS第29课:添加Canvas源
javascript·gis·map·mapbox·maplibre gl js
就叫_这个吧3 小时前
HTML常用标签及举例使用
前端·html
utf8mb4安全女神3 小时前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
YANQ6623 小时前
7.bundlesdf本地安装
前端·webpack·node.js