js实现上下分屏
实现上下分屏的基本思路
使用HTML和CSS创建两个固定高度的容器,分别放置上下两部分内容。通过JavaScript动态调整高度或处理交互逻辑。

HTML结构
<div class="split-container">
<div class="top-pane" id="topPane">
<!-- 上屏内容 -->
</div>
<div class="divider" id="divider"></div>
<div class="bottom-pane" id="bottomPane">
<!-- 下屏内容 -->
</div>
</div>
CSS样式
.split-container {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
.top-pane, .bottom-pane {
position: absolute;
width: 100%;
overflow: auto;
}
.top-pane {
top: 0;
height: 50%;
}
.bottom-pane {
bottom: 0;
height: 50%;
}
.divider {
position: absolute;
width: 100%;
height: 5px;
background-color: #ccc;
cursor: row-resize;
z-index: 100;
top: 50%;
}
JavaScript实现拖动调整
const divider = document.getElementById('divider');
const topPane = document.getElementById('topPane');
const bottomPane = document.getElementById('bottomPane');
let isDragging = false;
divider.addEventListener('mousedown', (e) => {
isDragging = true;
document.body.style.cursor = 'row-resize';
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const containerHeight = document.querySelector('.split-container').offsetHeight;
const newTopHeight = (e.clientY / containerHeight) * 100;
topPane.style.height = `${newTopHeight}%`;
bottomPane.style.height = `${100 - newTopHeight}%`;
divider.style.top = `${newTopHeight}%`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
document.body.style.cursor = '';
});
响应式处理
添加窗口大小变化的监听,确保分屏布局适应不同屏幕尺寸:

window.addEventListener('resize', () => {
const containerHeight = document.querySelector('.split-container').offsetHeight;
const topHeightPercent = (parseFloat(topPane.style.height) || 50);
topPane.style.height = `${topHeightPercent}%`;
bottomPane.style.height = `${100 - topHeightPercent}%`;
divider.style.top = `${topHeightPercent}%`;
});
替代方案:使用CSS Grid
对于不需要拖动调整的简单分屏,可以使用CSS Grid布局:
.grid-container {
display: grid;
grid-template-rows: 1fr 1fr;
height: 100vh;
}
.grid-top {
overflow: auto;
}
.grid-bottom {
overflow: auto;
}
注意事项
- 确保容器有明确的高度值(如100vh或固定像素值)
- 考虑为内容区域添加overflow属性处理内容溢出
- 移动端设备可能需要添加触摸事件支持
- 复杂的交互场景建议使用现成的库如Split.js






