Vue弹框拖拽功能

本文介绍了如何在Vue项目中使用自定义`v-drag`和`dragheader`指令,实现在页面上的元素拖动功能,同时处理弹框层叠问题。通过计算鼠标位置调整元素位置,并在全局注册中设置弹框层级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用该功能需要给具体的vue组件加上对应的标识

// v-drag和dragheader
<div class="Dispose_content" v-drag>
    <div class="bg_header cg_header dragheader">
    </div>
</div>

通过算出鼠标相对元素的位置 移动元素到当前鼠标的相对位置

import Vue from 'vue'
// 自定义拖拽指令
Vue.directive('drag', {
  // 指令的定义
  bind: function (el) {
    const odiv = el // 获取当前元素
    odiv.classList.add('popup-border')
    const oheader = el.querySelector('.dragheader') // querySelector的参数是选择器,任何选择器都可以作为它的参数
    if (oheader) {
      oheader.onmousedown = (e) => {
      // 算出鼠标相对元素的位置
        const disX = e.clientX - odiv.offsetLeft
        const disY = e.clientY - odiv.offsetTop
        let left = ''
        let top = ''
        document.onmousemove = (e) => {
        // 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
          left = e.clientX - disX
          top = e.clientY - disY
          // 绑定元素位置到positionX和positionY上面
          // 移动当前元素
          if (left <= 0) {
            left = 0
          } else if (left >= document.documentElement.clientWidth - odiv.offsetWidth) {
          // document.documentElement.clientWidth 屏幕的可视宽度
            left = document.documentElement.clientWidth - odiv.offsetWidth
          }
          if (top <= 50 && !odiv.className.split(' ').includes('unlimited')) {
            top = 50
          } else if (top >= document.documentElement.clientHeight - odiv.offsetHeight) {
          // document.documentElement.clientHeight 屏幕的可视高度
            top = document.documentElement.clientHeight - odiv.offsetHeight
          }
          odiv.style.left = left + 'px'
          odiv.style.top = top + 'px'
        }
        document.onmouseup = (e) => {
          document.onmousemove = null
          document.onmouseup = null
        }
        if (config.currentZIndex) {
          config.currentZIndex++
        } else {
          config.currentZIndex = 10
        }
        if (odiv.className.split(' ').includes('unlimited')) return
        odiv.style.zIndex = config.currentZIndex
      }
    }
  }
})

弹框拖拽功能会涉及到弹框层叠问题,当你点击某个弹框时,主动赋予比上一个弹框更高的层叠

在全局注册(register-components.js)组件时,将该js挂载到所有的组件中

主要实现方法:

    /*
     *@description: 设置当前的弹框层级置顶
    */
    mixinPopupIndex() {
      this.$nextTick(() => {
        if (!(this.$el instanceof HTMLElement)) return
        if (!this.$el.querySelector('.dragheader')) return
        config.currentZIndex ? (config.currentZIndex++) : (config.currentZIndex = 10)
        this.$el.style.zIndex = config.currentZIndex
      })
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值