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)
相关推荐
moxiaoran57533 小时前
uni-app萌宠案例学习笔记--页面布局和CSS样式设置
前端·css·uni-app
CrissChan4 小时前
Pycharm 函数注释
java·前端·pycharm
小小小小宇4 小时前
Vue.nextTick()笔记
前端
小约翰仓鼠6 小时前
vue3子组件获取并修改父组件的值
前端·javascript·vue.js
Lin Hsüeh-ch'in6 小时前
Vue 学习路线图(从零到实战)
前端·vue.js·学习
烛阴6 小时前
bignumber.js深度解析:驾驭任意精度计算的终极武器
前端·javascript·后端
计蒙不吃鱼6 小时前
一篇文章实现Android图片拼接并保存至相册
android·java·前端
全职计算机毕业设计7 小时前
基于Java Web的校园失物招领平台设计与实现
java·开发语言·前端
你的人类朋友7 小时前
✍️Node.js CMS框架概述:Directus与Strapi详解
javascript·后端·node.js