如何设置堆叠<div>边界:初始居中显示且支持用户垂直调整高度?
解决方案
问题1:页面加载时动态设置两个div高度,使边界位于屏幕中心
完全可以实现,提供两种可行方案:
- CSS纯方案:借助视口单位
vh和Flex布局实现,无需JavaScript。给父容器设置height: 100vh,并开启display: flex; flex-direction: column,两个子div分别设置flex: 1,它们会自动平分视口高度,边界自然落在屏幕中心。注意给html和body设置height: 100%; margin: 0,消除默认间距影响。 - JavaScript方案:页面加载时计算视口高度,将其均分后赋值给两个div,同时监听窗口
resize事件适配尺寸变化。示例代码:
function adjustDivHeights() { const viewportHeight = window.innerHeight; const halfHeight = viewportHeight / 2; const topDiv = document.getElementById('top-div'); const bottomDiv = document.getElementById('bottom-div'); topDiv.style.height = `${halfHeight}px`; bottomDiv.style.height = `${halfHeight}px`; } // 页面加载和窗口尺寸变化时执行 window.addEventListener('load', adjustDivHeights); window.addEventListener('resize', adjustDivHeights);
问题2:支持用户拖动边界调整两个div高度
可以实现,核心是通过JavaScript监听鼠标事件处理拖动逻辑,步骤如下:
- 在两个div之间添加一个拖动条元素,设置固定高度(如5px)、醒目背景色,以及
cursor: ns-resize提示可拖动。 - 监听拖动条的
mousedown事件,记录初始鼠标位置、两个div的当前高度。 - 在
mousemove事件中计算鼠标偏移量,动态调整两个div的高度,同时设置最小高度限制(避免div过小无法使用)。 - 监听
mouseup事件,移除拖动相关的事件监听,结束操作。
核心代码示例:
const resizer = document.getElementById('resizer'); const topDiv = document.getElementById('top-div'); const bottomDiv = document.getElementById('bottom-div'); let startY, initialTopHeight, initialBottomHeight; resizer.addEventListener('mousedown', (e) => { e.preventDefault(); startY = e.clientY; initialTopHeight = topDiv.offsetHeight; initialBottomHeight = bottomDiv.offsetHeight; document.addEventListener('mousemove', handleResize); document.addEventListener('mouseup', stopResize); }); function handleResize(e) { const delta = e.clientY - startY; const newTopHeight = initialTopHeight + delta; const newBottomHeight = initialBottomHeight - delta; // 限制最小高度为50px,可按需调整 if (newTopHeight >= 50 && newBottomHeight >= 50) { topDiv.style.height = `${newTopHeight}px`; bottomDiv.style.height = `${newBottomHeight}px`; } } function stopResize() { document.removeEventListener('mousemove', handleResize); document.removeEventListener('mouseup', stopResize); }
内容的提问来源于stack exchange,提问作者Jonathan Wood
相关产品推荐
相关产品推荐

