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

如何用JavaScript实现4行7列字母键盘网格并插入Bootstrap按钮

问题修复方案

问题原因

  • 外层#buttons-space元素已经自带row类,内部再次嵌套带row、container类的元素会触发Bootstrap栅格嵌套错误,是布局变为1行1列的核心原因
  • 仅编写了单行生成逻辑,没有添加4行的循环逻辑
  • 字母数组下标从0开始,循环从i=1启动会丢失第一个字母a
  • col-1搭配mx-2边距会超出Bootstrap单行12列的总宽度限制,导致列自动换行

修复后代码

JavaScript代码

var alphabet =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

function createKeyboard() {
  var space = document.getElementById("buttons-space");
  // 调整外层类避免栅格冲突
  space.className = "justify-content-center container";
  let charIndex = 0;
  // 循环生成4行
  for(let rowNum = 0; rowNum <4; rowNum++){
    var row = document.createElement("div");
    row.className = "row mb-2";
    space.appendChild(row); 
    // 每行生成7列
    for (var colNum = 0; colNum <7; ++colNum) {
      var col = document.createElement("div");
      // 用col-auto自适应内容宽度,避免栅格溢出
      col.className = "col-auto my-2 mx-2";
      row.appendChild(col); 
      if(charIndex < alphabet.length){
        var button = document.createElement("button");
        button.className = "btn btn-warning";
        button.style.height = "40px";
        button.style.width = "40px";
        button.id = alphabet[charIndex];
        button.innerText = alphabet[charIndex];
        col.appendChild(button);
        charIndex++;
      }
    }
  }
}
// 调用函数生成键盘
createKeyboard();

原有HTML代码无需修改

<div class="row justify-content-center container" id="buttons-space"></div>

实现效果说明

  • 自动生成4行7列的网格布局,前26个位置对应a-z的字母按钮,剩余2个位置留空
  • 完全通过JS实现,没有添加额外CSS
  • 兼容Bootstrap原生栅格规则,不会出现布局错乱

内容的提问来源于stack exchange,提问作者Ale.X.L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:54:00