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

基于Toggle Switch实现Div横竖切换与文本框重排的技术问询

解决方案

核心实现思路

不用仅依赖flex-direction切换布局,而是通过给容器切换自定义类,同时控制flex-direction、flex-wrap和子元素宽度,实现两种布局的无缝同步切换:

  • 垂直布局:容器设为flex-direction: column,所有文本框宽度100%,自然垂直排列
  • 水平布局:容器设为flex-direction: row + flex-wrap: wrap,每个文本框宽度设为calc(25% - 10px)(预留间距),自动每行排4个

完整代码示例

HTML部分

<div class="toggle-container">
  <label class="toggle-switch">
    <input type="checkbox" id="layoutToggle">
    <span class="slider"></span>
  </label>
  <span>切换布局</span>
</div>

<div class="top-container vertical">
  <input type="text" placeholder="文本框1">
  <input type="text" placeholder="文本框2">
  <input type="text" placeholder="文本框3">
  <input type="text" placeholder="文本框4">
  <input type="text" placeholder="文本框5">
  <input type="text" placeholder="文本框6">
  <input type="text" placeholder="文本框7">
  <input type="text" placeholder="文本框8">
</div>

CSS部分

/* 容器基础样式 */
.top-container {
  display: flex;
  gap: 10px;
  padding: 20px;
  border: 1px solid #eee;
  transition: all 0.3s ease;
}

/* 垂直布局样式 */
.top-container.vertical {
  flex-direction: column;
}
.top-container.vertical input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

/* 水平布局样式 */
.top-container.horizontal {
  flex-direction: row;
  flex-wrap: wrap;
}
.top-container.horizontal input {
  width: calc(25% - 10px);
  padding: 8px;
  box-sizing: border-box;
}

/* 开关样式 */
.toggle-switch {
  position: relative;
  display: inline-block;
  width: 48px;
  height: 24px;
}
.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}
.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}
input:checked + .slider {
  background-color: #2196F3;
}
input:checked + .slider:before {
  transform: translateX(24px);
}
.toggle-container {
  margin: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

JavaScript部分

const toggle = document.getElementById('layoutToggle');
const container = document.querySelector('.top-container');

toggle.addEventListener('change', function() {
  if (this.checked) {
    container.classList.replace('vertical', 'horizontal');
  } else {
    container.classList.replace('horizontal', 'vertical');
  }
});

关键细节说明

  • 用gap属性控制文本框间距,比margin更简洁且不会引发布局溢出
  • 水平布局时用calc(25% - 10px)计算宽度,减去gap值避免换行异常
  • 给容器添加transition属性,让布局切换有平滑过渡效果
  • 通过类切换而非直接修改样式属性,代码更易维护和扩展

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:35:05