如何按父容器宽度拆分子元素至不同.parent容器?
实现子元素自动拆分到多行
.parent容器的解决方案 问题分析
现有JS代码的核心缺陷:
- 未计算
.parent容器内的gap:24px间距,导致宽度计算偏差 - 累加所有按钮的总宽度而非当前行的宽度,拆分逻辑错误
- 仅移动触发溢出的单个按钮,未正确维护每行的按钮集合
修正后的完整代码
HTML(保持原结构不变)
<div class="wrapper"> <div class="parent"> <a href="#" class="child">Manufacturing & IOT</a> <a href="#" class="child">Software</a> <a href="#" class="child">High Tech</a> <a href="#" class="child">Media + Entertainment</a> <a href="#" class="child">Revenue Management</a> <a href="#" class="child">Recurring Billing</a> <a href="#" class="child">Recurring Payments</a> <a href="#" class="child">Reduce Time-to-Close</a> <a href="#" class="child">Usage-Based Pricing</a> <a href="#" class="child">Usage-Based Pricing</a> </div> </div>
CSS(保留原样式,确保伪元素和hover效果生效)
.wrapper { display: flex; justify-content: center; flex-wrap: wrap; max-width: 708px; margin: 0 auto; } .parent { display: inline-flex; flex-wrap: wrap; justify-content: center; gap: 24px; margin: 0 auto; max-width: 708px; position: relative; margin-bottom: 24px; } .parent::before, .parent::after { content: ''; width: 100vw; height: 48px; box-shadow: 5px 5px 100px 0px rgba(108, 123, 170, 0.24); border-radius: 40px; background-color: white; position: absolute; top: 0; z-index: -21; } .parent::before { right: calc(100% + 24px); } .parent::after { left: calc(100% + 24px); } .child { text-align: center; height: 48px; background-color: white; color: green; white-space: nowrap; border-radius: 40px; padding: 13px 24px; font-weight: 600; line-height: 48px; transition: color 0.5s ease, background-color 0.5s ease; box-shadow: 5px 5px 100px 0px rgba(108, 123, 170, 0.24); position: relative; } .child:hover { color: white; background-color: green; }
修正后的JavaScript代码
const btnsWrapper = document.querySelector('.wrapper'); const containerWidth = btnsWrapper.offsetWidth; const gap = 24; // 对应.parent的gap值 const initialParent = document.querySelector('.parent'); const btns = Array.from(initialParent.querySelectorAll('.child')); // 清空初始容器,重新分配按钮 initialParent.innerHTML = ''; let currentParent = initialParent; let currentRowWidth = 0; btns.forEach((btn) => { const btnWidth = btn.offsetWidth; // 计算加入当前按钮后的总宽度:已有宽度 + 按钮宽度 + (非首个按钮需加gap) const totalWidth = currentRowWidth + btnWidth + (currentRowWidth !== 0 ? gap : 0); if (totalWidth > containerWidth && currentRowWidth !== 0) { // 创建新的.parent容器并切换 const newParent = document.createElement('div'); newParent.classList.add('parent'); btnsWrapper.appendChild(newParent); currentParent = newParent; currentRowWidth = btnWidth; } else { // 更新当前行宽度 currentRowWidth = currentRowWidth === 0 ? btnWidth : currentRowWidth + gap + btnWidth; } currentParent.appendChild(btn); });
关键改进说明
- 宽度计算修正:加入了
.parent的gap间距,确保每行总宽度计算准确 - 行容器管理:实时维护当前行的容器和宽度,溢出时自动创建新的
.parent容器 - 初始容器重置:清空初始
.parent后重新分配按钮,保证最终DOM结构符合预期 - 效果保留:完全保留原有CSS样式,确保
.parent的伪元素和.child的hover交互正常生效
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

