You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在棋盘项目中实现棋子的拖拽与方格吸附功能?

实现可拖拽+方格吸附的棋盘棋子移动功能

核心实现思路

用HTML表格构建8x8棋盘,通过原生JavaScript处理拖拽事件,将棋子吸附到目标方格内,不涉及棋子移动合法性校验。


完整代码实现

HTML(含内嵌样式与初始化逻辑)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chess Drag & Snap</title>
    <!-- 内嵌样式替代外部CSS,保持简洁 -->
    <style>
        .chess-board { border-collapse: collapse; }
        .chess-cell {
            width: 50px;
            height: 50px;
            text-align: center;
            vertical-align: middle;
        }
        .chess-piece {
            width: 45px;
            height: 45px;
            cursor: grab;
        }
        .chess-piece:active { cursor: grabbing; }
    </style>
</head>
<body>
    <!-- 生成8x8棋盘 -->
    <table class="chess-board">
        <script>
            for (let row = 0; row < 8; row++) {
                document.write('<tr>');
                for (let col = 0; col < 8; col++) {
                    const bgColor = (row + col) % 2 === 1 ? '#769656' : '#eeeed2';
                    document.write(`<td class="chess-cell" style="background: ${bgColor}" data-row="${row}" data-col="${col}"></td>`);
                }
                document.write('</tr>');
            }
        </script>
    </table>

    <!-- 初始化棋子 -->
    <script>
        // 替换为你实际的棋子图片路径(对应你项目中的命名)
        const initialPieces = [
            { color: 'white', type: 'pawn', row: 1, col: 0 },
            { color: 'white', type: 'pawn', row: 1, col: 1 },
            { color: 'black', type: 'rook', row: 7, col: 7 },
            { color: 'black', type: 'knight', row: 7, col: 6 }
        ];

        initialPieces.forEach(p => {
            const pieceImg = document.createElement('img');
            pieceImg.src = `${p.color}_${p.type}.png`;
            pieceImg.className = 'chess-piece';
            pieceImg.draggable = true;

            // 放入对应初始格子
            const targetCell = document.querySelector(`[data-row="${p.row}"][data-col="${p.col}"]`);
            targetCell.appendChild(pieceImg);
        });
    </script>

    <!-- 拖拽逻辑 -->
    <script>
        let draggedPiece = null;

        // 拖拽开始:记录当前棋子
        document.addEventListener('dragstart', e => {
            if (e.target.classList.contains('chess-piece')) {
                draggedPiece = e.target;
                e.dataTransfer.setData('text', ''); // 兼容部分浏览器必须设置
            }
        });

        // 拖拽经过:允许放置
        document.addEventListener('dragover', e => e.preventDefault());

        // 放置棋子:吸附到目标方格
        document.addEventListener('drop', e => {
            e.preventDefault();
            if (!draggedPiece) return;

            const targetCell = e.target.closest('.chess-cell');
            if (!targetCell) return;

            // 清空目标方格并放入棋子
            targetCell.innerHTML = '';
            targetCell.appendChild(draggedPiece);
            draggedPiece = null;
        });
    </script>
</body>
</html>

关键说明

  1. 棋盘构建:通过循环生成8x8表格,每个方格用data-row和data-col标记位置,背景色交替模拟棋盘样式
  2. 拖拽逻辑:
    • dragstart:记录被拖拽的棋子
    • dragover:阻止默认行为,允许在方格上放置棋子
    • drop:找到目标方格,将棋子移入,实现方格吸附效果
  3. 图片适配:确保棋子图片命名与代码中${p.color}_${p.type}.png格式一致(比如white_pawn.png),直接替换路径即可

内容的提问来源于stack exchange,提问作者Alessandro Vasta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:44:57