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

如何通过DOM操作避免动态生成的网格元素自动换行

解决方法

问题根因

  • JS逻辑错误:makeBox函数内错误地将格子元素直接插入到了document.body,而非传入的行容器_parentBox,导致行容器上的white-space: nowrap规则完全无法作用到格子上。
  • CSS存在无效语法:div>div选择器下的第二条border属性带了单引号,属于非法CSS规则,不会生效。

修改后的代码

JS代码

let makeGrid = function(numberOfRows) {
  let y = 0;
  let x = 0;

  while (y < numberOfRows) {
    x = 0;

    let makeBox = function(_parentBox, _sizeOfBox) {
      let box = document.createElement('div');
      // 修复:将格子插入到对应行容器中
      _parentBox.appendChild(box);
      box.style.width = '28px';
      box.style.height = '28px';
      box.style.border = '1px solid white';
      box.style.display = 'inline-block';
      return box;
    };

    let makeRowBox = function(parentBox) {
      let box = document.createElement('div');
      parentBox.appendChild(box);
      // 显式给行容器设置不换行规则,优先级更高
      box.style.whiteSpace = 'nowrap';
      return box;
    };

    const rowBox = makeRowBox(document.body);

    while (x < numberOfRows) {
      makeBox(rowBox, 400);
      x = x + 1;
    }

    y = y + 1;
  }
};

makeGrid(50);

CSS代码

div {
  background-color: rgb(68, 157, 230);
  /* 如果需要横向滚动可改为 overflow-x: auto */
  overflow: hidden;
}

div>div {
  display: inline-block;
  border: 1px solid white;
  margin-right: 4px;
}

HTML代码(可保留原有内容)

<div style="white-space: nowrap;"></div>

修改完成后所有行内的格子都会保持横向排列不会自动换行,如果需要查看溢出的内容,只需将CSS中的overflow: hidden改为overflow-x: auto即可出现横向滚动条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:45:03