基于Vue2或Vue3实现任意上下左右拖拽悬浮的元素,且配置为自定义的全局指令

简介: 这篇文章介绍了如何在Vue 2或Vue 3项目中实现一个自定义的全局指令`v-dragSwitch`,用于创建可以任意方向拖拽并悬浮的元素,同时包含边界处理的逻辑。

前言

使用Vue实现任意上下左右拖拽悬浮的元素,以及具有边界处理的具体实现是网上的大神实现的,也不知是谁了。俺只不过是优化了一下皮毛,写了个在Vue2或Vue3的项目中的示例,配置自定义的全局指令,主要是方便下次使用,记录一下。

一、基于Vue2框架的项目

(1)在 /src/utils/ 目录中新建 diyVueDirectives.js

/**
 * 自定义拖拽指令
 */
const dragSwitch = {
   
   
  bind(el, binding, vnode, oldVnode) {
   
   
    // 判断是否可拖拽
    if (!binding.value) {
   
   
      return
    }

    // 获取相关元素
    const container = el.querySelector('.d-d_container')
    const header = el.querySelector('.d-d_container_header')
    header.style.cssText += ';cursor:move;'

    // 获取元素原有属性
    const sty = (function () {
   
   
      if ((document.body).currentStyle) {
   
   
        return (dom, attr) => dom.currentStyle[attr] // 兼容IE写法
      }
      return (dom, attr) => getComputedStyle(dom, null)[attr]
    })()

    /**
     * 鼠标按下事件
     */
    header.onmousedown = (e) => {
   
   
      const disX = e.clientX - header.offsetLeft
      const disY = e.clientY - header.offsetTop
      const screenWidth = document.body.clientWidth // document.body的可见区域宽度
      const screenHeight = document.documentElement.clientHeight // 可见区域高度(应为body高度,可某些环境下无法获取)

      const containerWidth = container.offsetWidth // 对话框宽度
      const containerheight = container.offsetHeight // 对话框高度

      const minContainerLeft = container.offsetLeft
      const maxContainerLeft = screenWidth - container.offsetLeft - containerWidth

      const minContainerTop = container.offsetTop
      const maxContainerTop = screenHeight - container.offsetTop - containerheight

      // 左偏移距离
      let styL = sty(container, 'left')
      if (styL === 'auto') {
   
   
        styL = '0px' // 兼容IE写法
      }

      // 上偏移距离
      let styT = sty(container, 'top')

      // 注意在IE中,第一次获取到的值为组件自带50%,移动之后赋值为px
      if (styL.includes('%')) {
   
   
        styL = +document.body.clientWidth * (+styL.replace(/%/g, '') / 100)
        styT = +document.body.clientHeight * (+styT.replace(/%/g, '') / 100)
      } else {
   
   
        styL = +styL.replace(/px/g, '')
        styT = +styT.replace(/px/g, '')
      }

      /**
       * 鼠标移动事件
       */
      document.onmousemove = function (e) {
   
   
        // 通过事件委托,计算移动的距离
        let left = e.clientX - disX
        let top = e.clientY - disY

        // 边界处理
        if (-(left) > minContainerLeft) {
   
   
          left = -(minContainerLeft)
        } else if (left > maxContainerLeft) {
   
   
          left = maxContainerLeft
        }

        if (-(top) > minContainerTop) {
   
   
          top = -(minContainerTop)
        } else if (top > maxContainerTop) {
   
   
          top = maxContainerTop
        }

        // 移动当前元素
        container.style.cssText += `;left:${
     
     left + styL}px;top:${
     
     top + styT}px;`
      }

      /**
       * 鼠标松开事件
       */
      document.onmouseup = function (e) {
   
   
        document.onmousemove = null
        document.onmouseup = null
      }

      return false
    }
  }
}

// 注册自定义拖拽指令
Vue.directive('dragSwitch', dragSwitch)

(2)在 main.js 中引入该指令集

// 引入 Vue 自定义指令集
import "@/utils/diyVueDirectives"

(3)任意在一个 vue 页面中使用 v-dragSwitch 指令即可

<template>
  <div style="width: 100%; height: 100%; position: relative; overflow: hidden; background-color: #dbe8ff">
    <!-- ^ 自定义拖拽模块一 -->
    <div class="d-d" v-dragSwitch="true">
      <div class="d-d_container" style="">
        <div class="d-d_container_header">标题一</div>
      </div>
    </div>
    <!-- / 自定义拖拽模块一 -->

    <!-- ^ 自定义拖拽模块二 -->
    <div class="d-d" v-dragSwitch="false">
      <div class="d-d_container" style="left: 100px; top: 100px">
        <div class="d-d_container_header">标题二</div>
      </div>
    </div>
    <!-- / 自定义拖拽模块二 -->

    <!-- ^ 自定义拖拽模块三 -->
    <div class="d-d" v-dragSwitch="true">
      <div class="d-d_container" style="right: 20px; top: calc(50% - 50px)">
        <div class="d-d_container_header">标题三</div>
      </div>
    </div>
    <!-- / 自定义拖拽模块三 -->
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    

    }
  },
  methods: {
    
    

  }
}
</script>

<style lang="less" scoped>
  .d-d {
    
    
    width: auto;
    height: auto;
    position: absolute;

    .d-d_container {
    
    
      width: 100px;
      height: 100px;
      position: fixed;
      background-color: #fff;
      user-select: none;

      .d-d_container_header {
    
    
        text-align: center;
        border-bottom: 1px solid #dcdfe6;
      }
    }
  }
</style>

二、基于Vue3框架的项目

(1)在 /src/utils/ 目录中新建 diyVueDirectives.ts

/**
 * 自定义拖拽指令
 */
const dragSwitch = {
   
   
  beforeMount(el: any, binding: any) {
   
   
    // 判断是否可拖拽
    if (!binding.value) {
   
   
      return
    }

    // 获取相关元素
    const container = el.querySelector('.d-d_container')
    const header = el.querySelector('.d-d_container_header')
    header.style.cssText += ';cursor:move;'

    // 获取元素原有属性
    const sty = (function () {
   
   
      if ((document.body as any).currentStyle) {
   
   
        return (dom: any, attr: any) => dom.currentStyle[attr] // 兼容IE写法
      }
      return (dom: any, attr: any) => getComputedStyle(dom, null)[attr]
    })()

    /**
     * 鼠标按下事件
     */
    header.onmousedown = (e: any) => {
   
   
      const disX = e.clientX - header.offsetLeft
      const disY = e.clientY - header.offsetTop
      const screenWidth = document.body.clientWidth // document.body的可见区域宽度
      const screenHeight = document.documentElement.clientHeight // 可见区域高度(应为body高度,可某些环境下无法获取)

      const containerWidth = container.offsetWidth // 对话框宽度
      const containerheight = container.offsetHeight // 对话框高度

      const minContainerLeft = container.offsetLeft
      const maxContainerLeft = screenWidth - container.offsetLeft - containerWidth

      const minContainerTop = container.offsetTop
      const maxContainerTop = screenHeight - container.offsetTop - containerheight

      // 左偏移距离
      let styL = sty(container, 'left')
      if (styL === 'auto') {
   
   
        styL = '0px' // 兼容IE写法
      }

      // 上偏移距离
      let styT = sty(container, 'top')

      // 注意在IE中,第一次获取到的值为组件自带50%,移动之后赋值为px
      if (styL.includes('%')) {
   
   
        styL = +document.body.clientWidth * (+styL.replace(/%/g, '') / 100)
        styT = +document.body.clientHeight * (+styT.replace(/%/g, '') / 100)
      } else {
   
   
        styL = +styL.replace(/px/g, '')
        styT = +styT.replace(/px/g, '')
      }

      /**
       * 鼠标移动事件
       */
      document.onmousemove = function (e) {
   
   
        // 通过事件委托,计算移动的距离
        let left = e.clientX - disX
        let top = e.clientY - disY

        // 边界处理
        if (-(left) > minContainerLeft) {
   
   
          left = -(minContainerLeft)
        } else if (left > maxContainerLeft) {
   
   
          left = maxContainerLeft
        }

        if (-(top) > minContainerTop) {
   
   
          top = -(minContainerTop)
        } else if (top > maxContainerTop) {
   
   
          top = maxContainerTop
        }

        // 移动当前元素
        container.style.cssText += `;left:${
     
     left + styL}px;top:${
     
     top + styT}px;`
      }

      /**
       * 鼠标松开事件
       */
      document.onmouseup = function (e: any) {
   
   
        document.onmousemove = null
        document.onmouseup = null
      }

      return false
    }
  }
}

/**
 * 定义指令集
 */
const diyVueDirectives = {
   
   
  install: function (app: any) {
   
   
    app.directive('dragSwitch', dragSwitch) // 注册自定义拖拽指令
  }
}

/**
 * 导出指令集
 */
export default diyVueDirectives

(2)在 main.ts 中引入该指令集

// 引入 Vue 自定义指令集并配置为全局属性
import diyVueDirectives from "@/utils/diyVueDirectives"

// 是否隐藏所有 console.log 信息打印,若注释此代码则显示,否则隐藏
// console.log = () => {}

app
.use(router)
.use(store)
.use(diyVueDirectives)
.use(ElementPlusPlugin)
.mount('#app')

(3)任意在一个 vue 页面中使用 v-dragSwitch 指令即可

<template>
  <div style="width: 100%; height: 100%; position: relative; overflow: hidden; background-color: #dbe8ff">
    <!-- ^ 自定义拖拽模块一 -->
    <div class="d-d" v-dragSwitch="true">
      <div class="d-d_container" style="">
        <div class="d-d_container_header">标题一</div>
      </div>
    </div>
    <!-- / 自定义拖拽模块一 -->

    <!-- ^ 自定义拖拽模块二 -->
    <div class="d-d" v-dragSwitch="true">
      <div class="d-d_container" style="left: 100px; top: 100px">
        <div class="d-d_container_header">标题二</div>
      </div>
    </div>
    <!-- / 自定义拖拽模块二 -->

    <!-- ^ 自定义拖拽模块三 -->
    <div class="d-d" v-dragSwitch="true">
      <div class="d-d_container" style="right: 20px; top: calc(50% - 50px)">
        <div class="d-d_container_header">标题三</div>
      </div>
    </div>
    <!-- / 自定义拖拽模块三 -->
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    

    }
  },
  methods: {
    
    

  }
}
</script>

<style lang="less" scoped>
  .d-d {
    
    
    width: auto;
    height: auto;
    position: absolute;

    .d-d_container {
    
    
      width: 100px;
      height: 100px;
      position: fixed;
      background-color: #fff;
      user-select: none;

      .d-d_container_header {
    
    
        text-align: center;
        border-bottom: 1px solid #dcdfe6;
      }
    }
  }
</style>

三、运行效果

目录
相关文章
|
4月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
707 139
|
4月前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
358 1
|
5月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
545 11
|
4月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
423 0
|
6月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
611 1
|
5月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
461 2
|
4月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
398 137
|
8月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
930 0
|
8月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
9月前
|
JavaScript 数据可视化 前端开发
基于 Vue 与 D3 的可拖拽拓扑图技术方案及应用案例解析
本文介绍了基于Vue和D3实现可拖拽拓扑图的技术方案与应用实例。通过Vue构建用户界面和交互逻辑,结合D3强大的数据可视化能力,实现了力导向布局、节点拖拽、交互事件等功能。文章详细讲解了数据模型设计、拖拽功能实现、组件封装及高级扩展(如节点类型定制、连接样式优化等),并提供了性能优化方案以应对大数据量场景。最终,展示了基础网络拓扑、实时更新拓扑等应用实例,为开发者提供了一套完整的实现思路和实践经验。
1159 78