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

Mancala游戏实现:如何让tr单元格内多张种子图片重叠居中不溢出

解决方案

你遇到的问题核心原因有两个:

  • 种子图片使用position: relative定位,相对定位的元素仍会占据常规文档流空间,图片数量多了自然会撑大单元格
  • 单元格没有设置溢出裁剪,也没有开启边框盒模型,超出内容不会被隐藏,边框额外占用空间也会挤压内部可用区域

修改后的CSS代码

#board {
    margin-left: auto;
    margin-right: auto;
    position: relative;
    top: 30%;
}

td {
    width: 75px;
    height: 75px;
    border: 3px solid darkred;
    border-radius: 40px;
    background: antiquewhite;
    /* 新增以下3行 */
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
}

table {
    border: 5px solid darkred;
    border-radius: 20px;
    background: burlywood;
}

修改后的JavaScript代码

function init_board() {
    const board = document.getElementById("board");
    
    for(let i = 0; i < 2; i++) {
        const tr = board.insertRow();
        if(i == 0) {
            tr.insertCell().setAttribute("rowSpan", "2");
        }

        for(let j = 0; j < 6; j++) {
            var x = tr.insertCell();
            // 这里的20可以替换成你需要的N值
            for(let k = 0; k < 20; k++) {
                var img = document.createElement("img");
                img.src = "images/seed.png";
                img.height = "10";
                img.width = "10";
                // 改为绝对定位,脱离文档流不占用单元格空间
                img.style.position = "absolute";
                // 调整随机偏移范围,保证图片完全在单元格内部
                // 单元格可用宽高为75-10=65px,所以偏移范围设为0-65
                img.style.left = Math.floor(Math.random() * 65) + "px";
                img.style.top = Math.floor(Math.random() * 65) + "px";
                
                x.appendChild(img);
            }
        }
        
        if(i == 0) {
            tr.insertCell().setAttribute("rowSpan", "2");
        }
    }
}

修改后种子图片会完全在圆形单元格内随机分布、互相重叠,不管N多大都不会撑大单元格,也不会溢出边界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:27:00