当前位置:首页 > JavaScript

js实现填字

2026-04-06 23:23:13JavaScript

实现填字游戏的 JavaScript 方法

基础结构设计

使用 HTML 和 CSS 创建填字游戏的网格布局。通过 <table><div> 构建网格,每个单元格对应一个字母位置。CSS 控制网格样式,如边框、背景色和单元格大小。

<div id="crossword-grid"></div>
#crossword-grid {
  display: grid;
  grid-template-columns: repeat(10, 30px);
  grid-gap: 1px;
}
.cell {
  width: 30px;
  height: 30px;
  border: 1px solid #000;
  text-align: center;
}

动态生成网格

通过 JavaScript 动态生成填字网格。定义一个二维数组表示填字布局,空白格用 null 或特定符号标记。

js实现填字

const gridData = [
  ['A', null, 'B', 'C'],
  [null, 'D', 'E', null],
  ['F', 'G', null, 'H']
];

function generateGrid() {
  const grid = document.getElementById('crossword-grid');
  gridData.forEach((row, rowIndex) => {
    row.forEach((cell, colIndex) => {
      const cellElement = document.createElement('div');
      cellElement.className = 'cell';
      if (cell) {
        cellElement.textContent = cell;
        cellElement.setAttribute('data-row', rowIndex);
        cellElement.setAttribute('data-col', colIndex);
      }
      grid.appendChild(cellElement);
    });
  });
}

用户输入处理

为单元格添加事件监听器,允许用户输入字母。限制输入长度为 1 个字符,并自动聚焦到下一个单元格。

document.querySelectorAll('.cell').forEach(cell => {
  cell.addEventListener('input', (e) => {
    const input = e.target.textContent.trim().toUpperCase();
    if (input.length > 1) {
      e.target.textContent = input[0];
    }
    moveToNextCell(e.target);
  });
});

function moveToNextCell(currentCell) {
  const row = parseInt(currentCell.getAttribute('data-row'));
  const col = parseInt(currentCell.getAttribute('data-col'));
  const nextCell = document.querySelector(`[data-row="${row}"][data-col="${col + 1}"]`);
  if (nextCell) nextCell.focus();
}

验证逻辑

实现答案验证功能,比较用户输入与预设答案是否匹配。可以实时验证或通过按钮触发。

js实现填字

const solution = [
  ['A', null, 'B', 'C'],
  [null, 'D', 'E', null],
  ['F', 'G', null, 'H']
];

function validateAnswers() {
  let isCorrect = true;
  document.querySelectorAll('.cell').forEach(cell => {
    const row = parseInt(cell.getAttribute('data-row'));
    const col = parseInt(cell.getAttribute('data-col'));
    if (solution[row][col] && cell.textContent !== solution[row][col]) {
      cell.style.backgroundColor = '#ffcccc';
      isCorrect = false;
    }
  });
  return isCorrect;
}

提示系统

添加数字标记提示功能,在格子角落显示题目编号。通过 CSS 伪元素实现小标数字。

.cell::before {
  content: attr(data-number);
  position: absolute;
  top: 0;
  left: 2px;
  font-size: 8px;
}
function addClueNumbers() {
  const clues = {
    '1': { row: 0, col: 0, direction: 'across' },
    '2': { row: 0, col: 2, direction: 'down' }
  };
  Object.keys(clues).forEach(number => {
    const { row, col } = clues[number];
    const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
    cell.setAttribute('data-number', number);
  });
}

键盘导航

增强用户体验,允许使用方向键在单元格间移动。监听键盘事件并调整焦点位置。

document.addEventListener('keydown', (e) => {
  const activeCell = document.activeElement;
  if (!activeCell.classList.contains('cell')) return;

  const row = parseInt(activeCell.getAttribute('data-row'));
  const col = parseInt(activeCell.getAttribute('data-col'));

  switch (e.key) {
    case 'ArrowUp':
      moveFocus(row - 1, col);
      break;
    case 'ArrowDown':
      moveFocus(row + 1, col);
      break;
    case 'ArrowLeft':
      moveFocus(row, col - 1);
      break;
    case 'ArrowRight':
      moveFocus(row, col + 1);
      break;
  }
});

function moveFocus(row, col) {
  const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
  if (cell) cell.focus();
}

标签: js
分享给朋友:

相关文章

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…