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)
相关推荐
掘金0128 分钟前
EmbedPDF Vue 版 完整正文文档 全网首发
前端
OpenTiny社区30 分钟前
操作ArkTS页面跳转及路由相关心得
前端·typescript·web·opentiny
xiaohua0708day31 分钟前
Lodash库
前端·javascript·vue.js
huakoh31 分钟前
Claude Code 从零到上手指南:国产工具链复现80% Agent能力,DeepSeek+LangChain实战
前端
Ankkaya33 分钟前
浏览器插件接入 Google 登录
前端
Asmewill35 分钟前
DeepAgents学习笔记一(构建深度多智能体)
前端
万物皆对象66635 分钟前
切换路由时页面空白问题(vue3)
前端·vue.js·typescript
突然好热36 分钟前
TS 调试技巧
前端·javascript·typescript
h64648564h37 分钟前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
令人头秃的代码0_038 分钟前
AI时代下,如何做原子代码拆分
前端