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

JS动态设置Grid属性值带引号致网格布局失效问题排查

问题原因与解决方案

问题出在你设置网格属性的方式上:你直接给DOM元素的属性赋值,而非通过style对象设置CSS样式。这种方式会让浏览器把属性值自动用引号包裹,导致CSS解析器无法识别repeat()语法,自然只显示单列。

正确做法

要动态设置CSS样式,必须通过元素的style属性操作:

function drawGrid(container) {
    const grid = document.createElement('div');
    grid.className = 'grid';
    let value = `repeat(${height}, auto)`;
    // 用style对象设置CSS属性
    grid.style.gridTemplateRows = value;
    value = `repeat(${width}, auto)`;
    grid.style.gridTemplateColumns = value;

    for (let i = 0; i < state.board_height; i++) {
        for (let j = 0; j < state.board_width; j++) {
            drawBox(grid, i, j);
        }
    }

    container.appendChild(grid);
}

也可以用短横线命名的写法(两种方式等效):

grid.style["grid-template-rows"] = value;
grid.style["grid-template-columns"] = value;

修改后,Chrome开发者工具里的样式会显示为无引号的正常值:

grid-template-columns: repeat(10, auto)
grid-template-rows: repeat(6, auto)

网格就能正常按行列布局了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:02:34