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)
相关推荐
Want59516 分钟前
HTML礼物圣诞树
前端·html
REDcker18 分钟前
Cursor Chrome DevTools MCP 配置指南 for Windows
前端·windows·chrome devtools
张可爱30 分钟前
20251115复盘记录:让分页乖乖“坐好”+ 卡片统一渐变描边与圆角
前端
Jonathan Star37 分钟前
基于 **Three.js** 开发的 3D 炮弹发射特效系统
javascript·数码相机·3d
Cache技术分享1 小时前
241. Java 集合 - 使用 Collections 工厂类处理集合
前端·后端
Lear1 小时前
解决Flex布局中overflow:hidden失效
前端
Heo1 小时前
原型理解从入门到精通
前端·javascript·后端
Heo1 小时前
通用会话控制方案
前端·javascript·后端
Heo1 小时前
跨域问题解决方案汇总
前端·javascript·后端
Yuroo zhou1 小时前
石油钻井、HDD、采矿:不同工况下,如何抉择您的陀螺定向短节?
前端·科技·硬件架构·钻井·采矿