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)
相关推荐
cyforkk4 分钟前
前端限流实战:从 429 状态码处理到消除“双重报错”
前端·状态模式
陈林梓21 分钟前
Qiankun 微前端配置详解
前端
英俊潇洒美少年26 分钟前
Vue3 的 JSX 函数组件,每次更新都会重新运行吗?
前端·javascript·vue.js
木斯佳26 分钟前
前端八股文面经大全:腾讯前端暑期AI面(2026-03-26)·面经深度解析
前端·人工智能·ai·智能体·暑期实习
invicinble31 分钟前
对于一个基本的前端后台管理框架的分析和认识
前端
恋猫de小郭32 分钟前
Android 17 新适配要求,各大权限进一步收紧,适配难度提升
android·前端·flutter
高桥凉介发量惊人35 分钟前
UI 与交互篇 (3/6):动画体系:隐式动画到自定义动画
前端
cyforkk38 分钟前
前端架构实战:当服务器关闭时,如何优雅提示 502 错误?
服务器·前端·架构
高桥凉介发量惊人43 分钟前
UI 与交互篇(1/6):组件化思路:从页面复制到可复用组件
前端
kyriewen43 分钟前
Generator 函数:那个能“暂停”的函数,到底有什么用?
前端·javascript·面试