js实现上下分屏
实现上下分屏的JavaScript方法
使用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%;
background-color: #f0f0f0;
}
.bottom-pane {
bottom: 0;
height: 50%;
background-color: #e0e0e0;
}
.divider {
position: absolute;
width: 100%;
height: 5px;
background-color: #ccc;
cursor: row-resize;
z-index: 10;
}
JavaScript实现
const divider = document.getElementById('divider');
const topPane = document.getElementById('topPane');
const bottomPane = document.getElementById('bottomPane');
let isDragging = false;
divider.addEventListener('mousedown', function(e) {
isDragging = true;
document.body.style.cursor = 'row-resize';
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
const containerHeight = document.querySelector('.split-container').offsetHeight;
const dividerPosition = e.clientY;
const topHeight = (dividerPosition / containerHeight) * 100;
const bottomHeight = 100 - topHeight;
topPane.style.height = `${topHeight}%`;
bottomPane.style.height = `${bottomHeight}%`;
divider.style.top = `${topHeight}%`;
});
document.addEventListener('mouseup', function() {
isDragging = false;
document.body.style.cursor = '';
});
使用现成库的方案
对于更复杂的需求,可以考虑使用现成的分屏库:

Split.js实现
import Split from 'split.js';
Split(['#topPane', '#bottomPane'], {
direction: 'vertical',
sizes: [50, 50],
minSize: [100, 100],
gutterSize: 5,
cursor: 'row-resize'
});
响应式处理
添加窗口大小变化时的处理逻辑:
window.addEventListener('resize', function() {
const container = document.querySelector('.split-container');
const currentTopHeight = parseFloat(topPane.style.height) || 50;
topPane.style.height = `${currentTopHeight}%`;
bottomPane.style.height = `${100 - currentTopHeight}%`;
divider.style.top = `${currentTopHeight}%`;
});
注意事项
- 确保容器元素有明确的高度设置
- 考虑添加最小高度限制防止面板太小
- 移动端设备可能需要添加触摸事件支持
- 复杂的应用场景建议使用专业库如Split.js或Golden Layout
以上方案提供了从基础到进阶的多种实现方式,可根据具体需求选择适合的方法。






