1/在根目录创建一个tz.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()
}
})
}
}
2/在main.js中引入
// 拖拽全局引入
import tz from "../tz"
//全局自定义指令。第一个参数是名字,第二个是引入的拖拽.js名字
Vue.directive('xin',tz)
3/在app.vue中给要加拖拽的盒子标签加上v-名字,这里就是v-xin
<template>
<div id="app">
<loading v-if="$store.state.loadingflag"></loading>
<div class="xin" v-xin >
<i class="iconfont icon-duanxin"></i>
</div>
<router-view/>
</div>
</template>
<script>
import loading from "./components/loading.vue";
export default {
components: {
loading
}
};
</script>
<style lang="scss">
#app{
height: 100vh;
}
.xin{
width: .6rem;
height: .6rem;
background-color: #007aff;
border-radius: 50%;
position: fixed;
right: .2rem;
bottom: 1rem;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999999;
i{
color:#fff;
font-size: .3rem;
}
}
</style>
效果就是下面的蓝色小信封: