当前位置:首页 > 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实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js轮播图实现原理

js轮播图实现原理

轮播图的基本原理 轮播图通过动态切换显示的内容(图片、文本等)实现视觉上的滑动效果。核心原理是利用CSS和JavaScript控制元素的显示与隐藏,或通过变换位置实现滑动动画。 实现方法一:…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…