<template>
<div class="splitter-container" @mouseleave="resetResize">
<div class="pane" :style="{ height: topHeight + 'px' }"></div>
<div class="divider" @mousedown="startResize"></div>
<div class="pane2">
<div style="width: 100%;height: 300px;background: #eee;">
wewe
</div>
rrr
</div>
</div>
</template>
<script>
export default {
data() {
return {
topHeight: 100, // 默认上栏高度
initialPosition: 0,
initialTopHeight: 0,
resizeTimeout: null,
};
},
methods: {
startResize(event) {
event.preventDefault();
this.initialPosition = event.clientY;
this.initialTopHeight = this.topHeight;
window.addEventListener('mousemove', this.resize);
window.addEventListener('mouseup', this.stopResize);
window.addEventListener('mouseleave', this.stopResize); // 添加鼠标离开事件
},
resize(event) {
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}
this.resizeTimeout = setTimeout(() => {
const delta = event.clientY - this.initialPosition;
// this.topHeight = Math.min(Math.max(this.initialTopHeight + delta, 100), 300); // 确保高度在100-300之间
this.topHeight = this.initialTopHeight + delta
this.resizeTimeout = null;
}, 10); // 防抖时间设置为10ms,
},
stopResize() {
window.removeEventListener('mousemove', this.resize);
window.removeEventListener('mouseup', this.stopResize);
window.removeEventListener('mouseleave', this.stopResize); // 移除鼠标离开事件
},
resetResize() {
// 如果用户在鼠标离开时正在调整大小,清除防抖定时器
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = null;
}
},
},
beforeUnmount() {
// 在组件卸载前清除所有事件监听器和定时器
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}
window.removeEventListener('mousemove', this.resize);
window.removeEventListener('mouseup', this.stopResize);
window.removeEventListener('mouseleave', this.stopResize);
},
};
</script>
<style>
.splitter-container {
display: flex;
flex-direction: column;
height: calc(100vh - 100px);
/* 容器高度 */
}
.pane {
overflow: auto;
background: red;
}
.pane2 {
flex: 1;
background: cyan;
overflow: auto;
}
.divider {
width: 100%;
height: 40px;
background-color: #ccc;
cursor: ns-resize;
position: relative;
}
</style>
其实就是colum布局,一直在调整上面的布局,下面的布局占据剩余部分,下面布局中子元素样式随便写,都可以滚动,还可以设置,上面布局的最小高度和最大高度
效果图