vue系列--vue封装拖拽指令v-drag

1.首先将下面的代码引入代码中

javascript 复制代码
export const initVDrag = (Vue) => {
  Vue.directive("drag", (el) => {
    const oDiv = el // 当前元素
    const minTop = oDiv.getAttribute("drag-min-top")
    const ifMoveSizeArea = 20
    oDiv.onmousedown = (e) => {
      let target = oDiv
      while (
        window.getComputedStyle(target).position !== "absolute" &&
        target !== document.body
        ) {
        target = target.parentElement
      }

      document.onselectstart = () => {
        return false
      }
      if (!target.getAttribute("init_x")) {
        target.setAttribute("init_x", target.offsetLeft)
        target.setAttribute("init_y", target.offsetTop)
      }

      const initX = parseInt(target.getAttribute("init_x"))
      const initY = parseInt(target.getAttribute("init_y"))

      // 鼠标按下,计算当前元素距离可视区的距离
      const disX = e.clientX - target.offsetLeft
      const disY = e.clientY - target.offsetTop
      document.onmousemove = (e) => {
        // 通过事件委托,计算移动的距离
        // 因为浏览器里并不能直接取到并且使用clientX、clientY,所以使用事件委托在内部做完赋值
        const l = e.clientX - disX
        const t = e.clientY - disY
        // 计算移动当前元素的位置,并且给该元素样式中的left和top值赋值
        target.style.left = l + "px"
        // target.style.top = (t < minTop ? minTop : t) + "px"
        target.style.top = t + "px"
        if (
          Math.abs(l - initX) > ifMoveSizeArea ||
          Math.abs(t - initY) > ifMoveSizeArea
        ) {
          target.setAttribute("dragged", "")
        } else {
          target.removeAttribute("dragged")
        }
      }
      document.onmouseup = (e) => {
        document.onmousemove = null
        document.onmouseup = null
        document.onselectstart = null
      }
      // return false不加的话可能导致黏连,拖到一个地方时div粘在鼠标上不下来,相当于onmouseup失效
      return false
    }
  })
}

2.在main.js中

复制代码
import {initVDrag} from "directives/dragscroll";
initVDrag(Vue)
相关推荐
Jerry15 分钟前
Compose 基础知识测试
前端
changuncle23 分钟前
Angular初学者入门第三课——工厂函数(精品)
前端·javascript·angular.js
ScottePerk41 分钟前
前端安全之XSS和CSRF
前端·安全·xss
PineappleCoder42 分钟前
Canvas 复杂交互步骤:从事件监听 to 重新绘制全流程
前端
日月晨曦1 小时前
JavaScript事件循环:一次浏览器线程的"约会"指南
javascript
s3xysteak1 小时前
我要成为vue高手01:上下文
前端·javascript·vue.js
复苏季风1 小时前
前端居中布局:从 "卡壳" 到 "精通" 的全方位指南
前端·css
qb1 小时前
vue3.5.18源码:computed 在发布订阅者模式中的双重角色
前端·vue.js·架构
南篱1 小时前
JavaScript原型链没那么难:一文彻底搞懂
javascript·面试
程序员张31 小时前
Vue3+ElementPlus倒计时示例
javascript·vue.js·前端框架