-需求: 实现div 可以拉伸变高
效果:
div拉伸效果
实现:
html 代码 ,随便写了个测试
<div class="test" :style="{height: boxHeight + 'px'}">
<div class="bottom-result-resizable" @mousedown="handleMouseDown"></div>
<div>123123123123123123123123123123123123123123123123123</div>
</div>
css:
<style lang="stylus" scoped>
.test
position: absolute
width 500px
left: 50px
bottom 20px
border: 1px solid
margin: 0 auto
.bottom-result-resizable
cursor: n-resize;
height: 3px
border-top: 1px solid red
&:hover
border-top-width: 3px
</style>
test 为要被拉伸的div。里面的div class="bottom-result-resizable" 为空的一条线,鼠标放上去的时候加粗效果,这是触发拉伸的地方。
重点为 @mousedown="handleMouseDown" 方法
data里定义:
boxHeight: 100, //当前容器高度
minHeight: 100, //容器最小高度
methods里方法
handleMouseDown(){
// 禁止用户选择网页中文字
document.onselectstart = () => false;
// 禁止用户拖动元素
document.ondragstart = () => false;
// 绑定鼠标移动事件
document.addEventListener('mousemove', this.handleMouseMove)
// 绑定鼠标放开事件
document.addEventListener('mouseup', this.handleMouseUp)
}, // move 事件
handleMouseMove(event) {
// 最小高度
const minHeight = this.minHeight;
// 最大高度 距离顶部100
const maxHeight = document.documentElement.clientHeight - 100;
// 最后高度
let box_height = document.documentElement.clientHeight - event.clientY;
if(box_height <= minHeight) {
box_height = minHeight;
}
else if(box_height > maxHeight){
box_height = maxHeight;
}
this.boxHeight = box_height
},
// up 事件
handleMouseUp() {
// 移除鼠标移动事件
document.removeEventListener('mousemove', this.handleMouseMove)
// 移除鼠标放开事件
document.removeEventListener('mouseup', this.handleMouseUp)
// 允许用户选择网页中文字
document.onselectstart = null
// 允许用户拖动元素
document.ondragstart = null
//记录高度 或者用localStorage 记录 (在初始加载的时候 把 boxHeight 赋值 记录的高度)
// this.Storage.set('bottomResultHeight',this.bottomResultHeight)
},