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)
相关推荐
PILIPALAPENG3 分钟前
第4周 Day 2:多步推理 Agent——让 Agent 学会"先想再干"
前端·人工智能·python
LPieces1 小时前
从零实现 AI 流式对话:SSE + Node.js 完整指南
前端
Crystal3281 小时前
【终极指南】前端方面解决 uni-app APP 端 SSE 流式请求被缓冲拦截、无法实时渲染的问题
android·前端·ai编程
BG1 小时前
利用Codex GPT-5.5 基于extended_image新增图片透视变换功能
前端·flutter
daols881 小时前
vue甘特图vxe-gantt如何实现拖拽任务条时如有已关联依赖线,同时更新依赖任务的日期的方式
javascript·vue.js·甘特图
小四的小六1 小时前
WebView 内存治理与稳定性实战:那些线上OOM教会我的事
前端·webview
我命由我123451 小时前
前端开发概念 - 无障碍树
javascript·css·笔记·学习·html·html5·js
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_29:(动态构建与更新 DOM 树)
前端·javascript·ui·html·html5·媒体
编程技术手记2 小时前
html table布局平衡
前端·html
huoyueyi2 小时前
3D数字孪生项目 LCP 优化指南
前端·3d·几何学