老闆:移動端這裏加個能夠返回首頁的按鈕,要能能夠拖動的。
我:好的 老闆。這個按鈕樣式有木有要求?
老闆:你本身看着辦。javascript
嗯。。。 自我感受還能夠,應該不用再改,今晚能夠準時下班了。html
相關文檔:vue
- [vue-自定義指令](https://cn.vuejs.org/v2/guide/custom-directive.html)
廢話很少說,直接上代碼。這裏都是一些加減法運算,相信你們應該可能都看得懂。java
/** * @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
全局註冊指令,因此須要引入一下。ide
// 引入指令 import vDrag from '@/directive/drag' Vue.directive('drag', vDrag)
<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>