Vue实现仿iPhone悬浮球的示例代码

2020-06-16 06:37:33易采站长站整理

悬浮球插件简单的效果图:

很遗憾,没找到太好的视频转gif的软件,压缩出来的大小超过了限制,就不放图了

可以参考其他人的图,效果一致:

简单实用案例:


<!-- 给定一个初始位置position,插槽中填写想滑动的部分 -->
<xuanfuqiu :position="position">
<d-add-button @click="addPigFarm" add-item="猪场"></d-add-button>
</xuanfuqiu>

原理示意图

请结合代码注释来理解

悬浮球插件代码如下:


<template>
<div>
<div class="xuanfu" id="moveDiv" :style="position"
@mousedown="down" @touchstart="down"
@mousemove="move" @touchmove="move"
@mouseup="end" @touchend="end">
<slot></slot>
</div>
</div>
</template>

<script>
export default {
name: "",
components: {},
props: {
// 通过position来设置初始定位
position: {
type: Object,
default: function() {
return {
top: "32.25rem",
left: "18.34375rem"
}
}
},
// 通过fixed来禁用自由移动
fixed: {
type: Boolean,
default: false
}
},
data() {
return {
flags: false,
positionTemp: { x: 0, y: 0 }, // 记录手指点击的位置
nx: '', ny: '', dx: '', dy: '', xPum: '', yPum: '',
}
},
watch: {},
computed: {},
methods: {
// 实现移动端拖拽
down(){
if (this.fixed) {
return
}

this.flags = true;
var touch;
// 该if判断是用touch还是mouse来移动
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
this.positionTemp.x = touch.clientX; // 手指点击后的位置
this.positionTemp.y = touch.clientY;

this.dx = moveDiv.offsetLeft; // 移动的div元素的位置
this.dy = moveDiv.offsetTop;

// console.log("moveDiv.offsetLeft", moveDiv.offsetLeft)
// console.log("touch.clientX", touch.clientX)
},
move(){
if(this.flags) {
var touch ;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
this.nx = touch.clientX - this.positionTemp.x; // 手指移动的变化量
this.ny = touch.clientY - this.positionTemp.y;

this.xPum = this.dx + this.nx; // 移动后,div元素的位置