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>

總結

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章