vue移动端可拖动div

一、plugins下新建drag.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()
      }
    })
  }
}
二、在main.js中引入drag.js并全局注册指令
// 引入指令
import vDrag from '@/plugins/drag'
Vue.directive('drag', vDrag)
三、在需要拖动的元素上添加 v-drag 指令
<div class="submitbtn"  v-drag>提交</div>


<style lang="scss" scoped>
  .submitbtn {
    position: fixed;
    right: 76%;
    bottom: 20%;
    border-radius: 24px;
    width: 80px;
    height: 40px;
    background-color: #3A8C50;
    color: #fff;
    line-height: 40px;
    z-index: 99;
  }
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值