如何调整Bootstrap 4栅格系统实现移动端表单优雅适配
实现移动端每行一个输入框的三种方案
一、Bootstrap 原生响应式类(最推荐)
Bootstrap 4 本身自带响应式列布局能力,无需额外写 CSS 或 JS,直接修改列类即可实现需求:
<div class="row"> <div class="col-md"> <input asp-for="First_Name_AR" class="form-control" /> </div> <div class="col-md"> <input asp-for="Second_Name_AR" class="form-control" /> </div> <div class="col-md"> <input asp-for="Father_Name_AR" class="form-control" /> </div> </div>
- 原理:
col-md表示在屏幕宽度 ≥768px(中等屏幕)时,列平分宽度;在屏幕 <768px(移动端)时,自动占满整行,自然实现每行一个输入框。
二、CSS @media 查询实现
如果不想修改原有 HTML 结构,可通过媒体查询强制移动端列占满整行:
/* 针对 Bootstrap 的 xs 断点(屏幕宽度 <576px) */ @media (max-width: 575.98px) { /* 给表单所在的 row 加个专属类,避免影响全局 row */ .form-multi-row .col { flex: 0 0 100%; max-width: 100%; margin-bottom: 1rem; /* 可选:增加输入框间距,优化移动端体验 */ } }
对应 HTML 只需给 row 加类:
<div class="row form-multi-row"> <div class="col">...</div> <div class="col">...</div> <div class="col">...</div> </div>
三、JavaScript 动态实现
若需更灵活的动态控制(比如根据特殊条件调整布局),可通过 JS 监听窗口尺寸变化:
方案1:动态修改样式
function adjustFormLayout() { const cols = document.querySelectorAll('.form-multi-row .col'); const isMobile = window.innerWidth < 576; cols.forEach(col => { if (isMobile) { col.style.flex = '0 0 100%'; col.style.maxWidth = '100%'; col.style.marginBottom = '1rem'; } else { // 恢复默认样式 col.style.flex = ''; col.style.maxWidth = ''; col.style.marginBottom = ''; } }); } // 页面加载和窗口 resize 时触发 window.addEventListener('load', adjustFormLayout); window.addEventListener('resize', adjustFormLayout);
方案2:动态重组 DOM 结构(完全匹配你想要的多行结构)
// 标记是否已重组,避免重复操作 let isRestructured = false; function restructureFormRows() { const originalRow = document.querySelector('.form-multi-row'); const isMobile = window.innerWidth < 576; if (isMobile && !isRestructured) { const cols = Array.from(originalRow.querySelectorAll('.col')); // 移除原 row 内的所有列 cols.forEach(col => originalRow.removeChild(col)); // 为每个列创建独立 row 并插入 cols.forEach(col => { const newRow = document.createElement('div'); newRow.className = 'row form-multi-row'; newRow.appendChild(col); originalRow.parentNode.insertBefore(newRow, originalRow); }); // 删除原空 row originalRow.parentNode.removeChild(originalRow); isRestructured = true; } else if (!isMobile && isRestructured) { // 屏幕变大时恢复原结构 const singleRows = document.querySelectorAll('.form-multi-row'); const newRow = document.createElement('div'); newRow.className = 'row form-multi-row'; singleRows.forEach(row => { const col = row.querySelector('.col'); if (col) newRow.appendChild(col); row.parentNode.removeChild(row); }); // 插入重组后的 row document.querySelector('.form-container').appendChild(newRow); // 替换为你的表单容器选择器 isRestructured = false; } } window.addEventListener('load', restructureFormRows); window.addEventListener('resize', restructureFormRows);
内容的提问来源于stack exchange,提问作者Khaled Helwane
相关产品推荐
相关产品推荐

