效果如图:

直接代码实现
<template>
<div class="box">
<div class="left" :style="{width:`calc(${leftWidthRate}% - 2px)`}"></div>
<div class="resize" @mousedown="dragDiv($event)"></div>
<div class="right" :style="{width:`calc(100% - ${leftWidthRate}% - 2px)`}"></div>
</div>
</template>
<script setup lang="ts">
import {ref} from "vue";
const leftWidthRate = ref(30)
const dragDiv = (e: any) => {
let box = document.getElementsByClassName('box')
let left = document.getElementsByClassName('left')
let boxWidth = box[0].offsetWidth
let leftWidth = left[0].offsetWidth
let minRightRate = parseFloat((200 / boxWidth * 100).toFixed(4))
let minLeftRate = parseFloat((200 / boxWidth * 100).toFixed(4))
// 鼠标开始位置
let startX = e.clientX
// 鼠标拖拽事件
document.onmousemove = function (e: any) {
// 鼠标结束位置
let endX = e.clientX
// 鼠标偏移量:取绝对值
let distX = Math.abs(endX - startX)
// 鼠标向右滑动
if (endX > startX) {
// 移动后左边div比率
let leftDivWidthRate = parseFloat(((leftWidth + distX) / boxWidth * 100).toFixed(4));
if ((parseFloat('100') - leftDivWidthRate) > minRightRate) {
leftWidthRate.value = leftDivWidthRate
}
}
// 鼠标向右滑动
if (endX < startX) {
// 移动后左边div比率
let leftDivWidthRate = parseFloat(((leftWidth - distX) / boxWidth * 100).toFixed(4));
if (leftDivWidthRate > minLeftRate) {
leftWidthRate.value = leftDivWidthRate
}
}
}
// 鼠标松开事件
document.onmouseup = (e: any) => {
document.onmousemove = null
document.onmouseup = null
}
}
</script>
<style lang="scss" scoped>
.box {
position: relative;
width: 100%;
height: 100%;
.left {
float: left;
width: calc(30% - 2px);
height: 100%;
background-color: green;
}
.resize {
float: left;
width: 4px;
height: 100%;
font-weight: 500;
color: gray;
cursor: w-resize;
}
.right {
float: left;
width: calc(70% - 2px);
height: 100%;
background-color: yellow;
}
}
</style>
有部分问题:鼠标有时松开时,鼠标按压事件还在生效,仍然还可以滑动。后续待解决,欢迎技术交流
1765

被折叠的 条评论
为什么被折叠?



