如何用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
相关产品推荐
相关产品推荐

