vue 自定义指令 -- 移动端 touch拖拽

简介

老板:移动端这里加个可以返回首页的按钮,要能可以拖动的。
我:好的 老板。这个按钮样式有木有要求?
老板:你自己看着办。
在这里插入图片描述

效果

在这里插入图片描述
嗯。。。 自我感觉还可以,应该不用再改,今晚可以准时下班了。

代码

相关文档:
- vue-自定义指令

废话不多说,直接上代码。这里都是一些加减法运算,相信大家应该可能都看得懂。

drag.js
/**
 * @description 移动端拖拽指令
 * @author 谭上彪
 * @date 2020-5-21 14:36:13
 * */
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全局注册指令,所以需要引入一下。

main.js
// 引入指令
import vDrag from '@/directive/drag'

Vue.directive('drag', vDrag)
toHome.vue
<template>
  <div class="to-home" v-drag @click="$router.push({ name: 'home' })">
    <i class="fa fa-home"></i>
  </div>
</template>

<script>
  export default {
    name: 'to-home'
  }
</script>

<style scoped>
  .to-home {
    position: fixed;
    z-index: 99;
    right: 10px;
    bottom: 85px;
    width: 40px;
    height: 40px;
    box-shadow: 0 2px 4px #ddd;
    border-radius: 50%;
    color: #fff;
    font-size: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #1989fa;
  }
</style>

总结

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40411946/article/details/106259829