全局自定义拖拽vue

本文介绍了如何在Vue项目中实现全局自定义拖拽功能。首先,在根目录创建tz.js,然后在main.js中引入并注册为Vue的自定义指令。最后,在app.vue组件中应用该指令,实现拖拽效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1/在根目录创建一个tz.js

export default {
    inserted(el) {
        let switchPos = {
            x: 10,
            y: 85,
            startX: 0,
            startY: 0,
            endX: 0,
            endY: 0
        }
        el.addEventListener('touchstart', function (e) {
            console.log(e)
            switchPos.startX = e.touches[0].pageX
            switchPos.startY = e.touches[0].pageY
        })
        el.addEventListener('touchend', function (e) {
            switchPos.x = switchPos.endX
            switchPos.y = switchPos.endY
            switchPos.startX = 0
            switchPos.startY = 0
        })
        el.addEventListener('touchmove', function (e) {
            if (e.touches.length > 0) {
                let offsetX = e.touches[0].pageX - switchPos.startX
                let offsetY = e.touches[0].pageY - switchPos.startY
                let x = switchPos.x - offsetX
                let y = switchPos.y - offsetY
                if (x + el.offsetWidth > document.documentElement.offsetWidth) {
                    x = document.documentElement.offsetWidth - el.offsetWidth
                }
                if (y + el.offsetHeight > document.documentElement.offsetHeight) {
                    y = document.documentElement.offsetHeight - el.offsetHeight
                }
                if (x < 0) {
                    x = 0
                }
                if (y < 0) {
                    y = 0
                }
                el.style.right = x + 'px'
                el.style.bottom = y + 'px'
                switchPos.endX = x
                switchPos.endY = y
                e.preventDefault()
            }
        })
    }
}

2/在main.js中引入

// 拖拽全局引入

import tz from "../tz"

//全局自定义指令。第一个参数是名字,第二个是引入的拖拽.js名字

Vue.directive('xin',tz)

 3/在app.vue中给要加拖拽的盒子标签加上v-名字,这里就是v-xin

<template>
  <div id="app">
    <loading  v-if="$store.state.loadingflag"></loading>
    <div class="xin" v-xin >
      <i class="iconfont icon-duanxin"></i>
    </div>
    <router-view/>
  </div>
</template>
<script>
import  loading  from "./components/loading.vue";
export default {
  components: {
    loading
  }
};
</script>
<style lang="scss">
#app{
  height: 100vh;
}
.xin{
  width: .6rem;
  height: .6rem;
  background-color: #007aff;
  border-radius: 50%;
  position: fixed;
  right: .2rem;
  bottom: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999999;
  i{
    color:#fff;
    font-size: .3rem;
  }
}
</style>

效果就是下面的蓝色小信封:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值