老板:移动端这里加个能够返回首页的按钮,要能能够拖动的。
我:好的 老板。这个按钮样式有木有要求?
老板:你本身看着办。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>