此组件以vue2为基础的demo,源码放在最后,可以直接复制到index.html文件运行
首先是鼠标控制交互,用绝对定位把一个元素放到拖动的的位置,设置css属性:
cursor: col-resize;
剩下的也简单了,监听鼠标位置,记录上次鼠标位置,计算出移动的x轴距离或者y轴距离
直接上代码,剩下的可以自己搞成vue2组件,代码较少,改成vue3或react等框架也比较简单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.body {
display: flex;
align-items: stretch;
height: 300px;
}
.left {
min-width: 100px;
width: 120px;
max-width: 300px;
border: 1px solid #999;
position: relative;
background: #999;
}
.bar {
display: inline-block;
width: 10px;
height: 100%;
position: absolute;
background: blue;
right: -5px;
top: 0;
cursor: col-resize;
}
.right {
flex-grow: 1;
border: 1px solid #999;
background: #ccc;
}
</style>
<body>
<div class="body" id="app">
<div class="left" :style="{width:`${leftWidth}px`}">
左
<div class="bar" ref="bar"></div>
</div>
<div class="right">右</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data() {
return {
left: 0, //组件控制横坐标
leftWidth: 120,//左边bar默认宽度
isControl: false,//正在控制鼠标
}
},
created() {
this.$nextTick(() => {
this.$refs.bar.onmousedown = () => {
document.onmousedown = (e) => {
this.isControl = true
this.left = e.clientX
}
document.onmousemove = (e) => {
//鼠标点击后进入控制模式
if (this.isControl) {
this.leftWidth = e.clientX - this.left + this.leftWidth //改变bar宽度
this.left = e.clientX //更新旧坐标
}
};
document.onmouseup = () => {
this.isControl = false
console.log('抬起鼠标,拖拽结束了')
// 拖拽结束执行一些方法
};
};
})
}
})
</script>
</html>