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)
相关推荐
正小安1 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光3 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   3 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   3 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web3 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常3 小时前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇4 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr4 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho5 小时前
【TypeScript】知识点梳理(三)
前端·typescript