js实现填字
实现填字游戏的 JavaScript 方法
基础实现思路
使用 HTML 表格构建填字网格,通过 JavaScript 动态生成字母输入框,绑定事件监听实现交互。核心步骤包括初始化网格、验证输入、提示功能等。
HTML 结构示例
<div id="crossword-container"></div>
核心代码实现
初始化网格
function createGrid(rows, cols) {
const container = document.getElementById('crossword-container');
const table = document.createElement('table');
for (let i = 0; i < rows; i++) {
const tr = document.createElement('tr');
for (let j = 0; j < cols; j++) {
const td = document.createElement('td');
const input = document.createElement('input');
input.type = 'text';
input.maxLength = 1;
input.dataset.row = i;
input.dataset.col = j;
td.appendChild(input);
tr.appendChild(td);
}
table.appendChild(tr);
}
container.appendChild(table);
}
验证答案逻辑
function checkSolution(solutionMatrix) {
const inputs = document.querySelectorAll('input');
let isCorrect = true;
inputs.forEach(input => {
const row = parseInt(input.dataset.row);
const col = parseInt(input.dataset.col);
if (input.value.toUpperCase() !== solutionMatrix[row][col]) {
isCorrect = false;
input.classList.add('incorrect');
} else {
input.classList.remove('incorrect');
}
});
return isCorrect;
}
进阶功能实现
键盘导航
function setupKeyboardNavigation() {
document.querySelectorAll('input').forEach(input => {
input.addEventListener('keyup', (e) => {
const row = parseInt(e.target.dataset.row);
const col = parseInt(e.target.dataset.col);
if (e.key.match(/^[a-zA-Z]$/)) {
// 自动聚焦下一个输入框
const nextInput = document.querySelector(
`input[data-row="${row}"][data-col="${col + 1}"]`
);
if (nextInput) nextInput.focus();
}
});
});
}
提示系统

function showHint(row, col, letter) {
const input = document.querySelector(
`input[data-row="${row}"][data-col="${col}"]`
);
input.value = letter;
input.classList.add('hint');
}
样式优化建议
table {
border-collapse: collapse;
margin: 20px auto;
}
td {
border: 1px solid #ddd;
width: 30px;
height: 30px;
text-align: center;
}
input {
width: 100%;
height: 100%;
border: none;
text-align: center;
text-transform: uppercase;
font-size: 16px;
}
.incorrect {
background-color: #ffcccc;
}
.hint {
color: #6666ff;
}
数据结构示例
// 答案矩阵示例
const solution = [
['H', 'E', 'L', 'L', 'O'],
['W', '', 'O', '', 'L'],
['O', '', 'R', '', 'D'],
['R', 'L', 'D', 'O', 'W']
];
// 初始化 4x5 的填字游戏
createGrid(4, 5);
setupKeyboardNavigation();
通过以上方法可实现基础填字游戏功能,可根据需求扩展词库加载、难度分级等特性。






