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

如何设置堆叠<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监听鼠标事件处理拖动逻辑,步骤如下:

  1. 在两个div之间添加一个拖动条元素,设置固定高度(如5px)、醒目背景色,以及cursor: ns-resize提示可拖动。
  2. 监听拖动条的mousedown事件,记录初始鼠标位置、两个div的当前高度。
  3. 在mousemove事件中计算鼠标偏移量,动态调整两个div的高度,同时设置最小高度限制(避免div过小无法使用)。
  4. 监听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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:12:53