vue3+vite实现左右DIV拖拽(优化版)

在这里插入图片描述

<template>
  <el-card body-style="height: calc(100vh - 162px)">
    <div class="metamodelBox">
      <div class="leftBox" :style="{width:`calc(${defaultLeftWidthRate}% - 2px)`}"></div>
      <div class="resize"/>
      <div class="rightBox" :style="{width:`calc(100% - ${defaultLeftWidthRate}% - 2px)`}"></div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";

onMounted(() => {
  dragDiv()
})

const defaultLeftWidthRate = ref(20)
const dragDiv = () => {
  let resize = document.getElementsByClassName('resize')
  let box = document.getElementsByClassName('metamodelBox')
  let left = document.getElementsByClassName('leftBox')
  for (let i = 0; i < resize.length; i++) {
    // 鼠标按下事件
    resize[i].onmousedown = function (e: any) {
      let boxWidth = box[i].offsetWidth
      let leftWidth = left[i].offsetWidth
      let minLeftWidthRate = parseFloat((100 / boxWidth * 100).toFixed(4))
      let minRightWidthRate = parseFloat((100 / 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) {
          let moveLate = parseFloat(((leftWidth + distX) / boxWidth * 100).toFixed(4));
          if ((parseFloat('100') - moveLate) > minRightWidthRate) {
            defaultLeftWidthRate.value = moveLate
          }
        }
        // 向左拖拽
        if (endX < startX) {
          let moveLate = parseFloat(((leftWidth - distX) / boxWidth * 100).toFixed(4));
          if (moveLate > minLeftWidthRate) {
            defaultLeftWidthRate.value = moveLate
          }
        }
      }
      // 鼠标松开事件
      document.onmouseup = function (e: any) {
        document.onmousemove = null
        document.onmouseup = null
        resize[i].releaseCapture && resize[i].releaseCapture() //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
      }
      resize[i].setCapture && resize[i].setCapture() //该函数在属于当前线程的指定窗口里设置鼠标捕获
      return false
    }
  }
}

</script>

<style lang="scss">
.metamodelBox {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
}

.metamodelBox .leftBox {
  position: relative;
  width: calc(20% - 2px);
  height: 100%;
  background-color: green;
}

.metamodelBox .resize {
  position: relative;
  width: 4px;
  height: 100%;
  color: gray;
  background: rgb(214, 214, 214);
  cursor: w-resize;
}

.metamodelBox .rightBox {
  position: relative;
  width: calc(80% - 2px);
  height: 100%;
  background-color: yellow;
}

</style>```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值