如何用HTML、CSS和JS实现可拖拽联动的双面板布局?
双面板横向拖拽联动布局解决方案
要实现双面板拖拽时宽度联动,同时满足「第二个面板宽度达视口30%时,第一个自动变为70%」的需求,核心是只对单个面板设置拖拽逻辑,利用flex布局特性让另一面板自动填充剩余空间,再添加阈值吸附逻辑。以下是修改后的完整实现:
完整代码
<style> * { margin: 0; padding: 0; box-sizing: border-box; } .container { width: 100vw; height: 100vh; display: flex; background-color: #eee; } .section { height: 100%; padding: 1rem; } .section:first-child { width: 70vw; background-color: #f5f5f5; border-right: 5px solid #111; cursor: col-resize; overflow: auto; } .section:last-child { flex: 1; /* 自动填充左侧面板剩余宽度 */ background-color: #e0e0e0; } </style> <div class="container"> <div class="section">Section 0</div> <div class="section">Section 1</div> </div> <script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script> <script> const container = document.querySelector('.container'); const leftPanel = document.querySelector('.section:first-child'); let viewportWidth = window.innerWidth; const threshold = 0.3 * viewportWidth; // 视口30%的宽度阈值 interact(leftPanel) .resizable({ edges: { top: false, left: false, bottom: false, right: true }, restrictEdges: { outer: 'parent', endOnly: true }, restrictSize: { min: { width: 100 }, max: { width: viewportWidth - 100 } } }) .on('resizemove', function (event) { let newLeftWidth = event.rect.width; const rightPanelWidth = container.offsetWidth - newLeftWidth; // 接近阈值时自动吸附到70%-30%比例 if (Math.abs(rightPanelWidth - threshold) < 20) { newLeftWidth = 0.7 * viewportWidth; } leftPanel.style.width = `${newLeftWidth}px`; }); // 窗口 resize 时更新阈值 window.addEventListener('resize', () => { viewportWidth = window.innerWidth; }); </script>
关键改进点
- 联动逻辑简化:容器用flex布局,右侧面板设
flex:1,自动填充左侧面板剩余空间,无需手动同步两个面板宽度。 - 单一拖拽目标:仅对左侧面板的右边缘设置拖拽,避免重复逻辑,减少代码冗余。
- 阈值吸附:通过计算右侧面板宽度与视口30%阈值的差值,拖拽接近该值时自动锁定70%-30%的比例。
- 拖拽范围限制:添加最小/最大宽度限制,避免面板被拖拽至过窄或消失。
内容的提问来源于stack exchange,提问作者Batu A.
相关产品推荐
相关产品推荐

