先来看看实现效果:
QQ录屏20220403095856
下面是实现代码:
<template>
<section class="section">
<div class="left" ref="left">
这是左边的div
<div class="box" ref="box"></div>
</div>
<div class="right" ref="right">
这是右边的div
</div>
</section>
</template>
<script>
export default {
name: 'Test',
mounted() {
this.init()
},
methods: {
init() {
let left = this.$refs.left
let right = this.$refs.right
let box = this.$refs.box
// firstX鼠标开始坐标位置,endX鼠标结束坐标位置,startWidth左边div开始宽度
let firstX, endX, startWidth
function myFunction(e) {
// 划过左边线
endX = e.clientX - firstX
// 获取移动的距离
left.style.width = startWidth + endX + 'px'
}
function selectStart(flag) {
left.onselectstart = function() {
return flag
}
right.onselectstart = function() {
return flag
}
}
box.addEventListener('mousedown',function(e) {
// 当鼠标点击移动开始不选中div里的内容
selectStart(false)
startWidth = left.offsetWidth // 起始宽
firstX = e.clientX // 起始点
document.addEventListener('mousemove',myFunction) // 开始移动
})
box.addEventListener('mouseleave',function(e) {
document.removeEventListener("mousemove", myFunction) // 结束移动
})
document.addEventListener('mouseup', function() {
// 当鼠标点击移动结束恢复选中div里的内容
selectStart(true)
// 移除移动事件,注意:移除事件的回调函数必须和注册事件是同一个,要不然移除不了哦!
document.removeEventListener("mousemove", myFunction) // 结束移动
})
}
}
}
</script>
<style lang="scss" scoped>
* {
margin: 0;
padding: 0;
}
.section {
width: 100%;
height: 100%;
display: flex;
}
div.right {
background-color: #00B83F;
height: 100%;
flex: 1;
}
div.left {
width: 200px;
background-color: #FFB951;
z-index: 1;
height: 100%;
position: relative;
.box {
width: 50px;
height: 50px;
cursor: col-resize;
background: red;
position: absolute;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
}
</style>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)