<template>
<view class="content">
<view :style="{'transform':'translate3d('+xMove+'px,'+yMove+'px,0)'}" class="touch" @touchstart="handleStart" @touchmove="handleMove" @touchend="handleEnd">↑</view>
</view>
</template>
<script>
var curPoint = {
x: 0,
y: 0
}; // 记录原点
var startPoint = {};
// 标志位(只触发点击事件按,并没有移动-就不必触发end事件)
var isTouchMove = false;
export default {
data() {
return {
xMove: 0,
yMove: 0
};
},
onLoad() {},
mounted() {
// 想通过获取节点来实现动态移动--这条路没有走通
// let view = uni.createSelectorQuery().in(this);
// view.select('.touch').boundingClientRect(data => {
// console.log(data)
// data.top = 100
// }).exec();
// let view = uni.createSelectorQuery().select('.touch');
// view.fields({rect: true},data => {
// console.log(data)
// data.top = 100
// }).exec();
},
methods: {
handleStart(ev) {
// console.log('start',ev);
// 记录一开始手指按下的坐标
var touch = ev.changedTouches[0];
startPoint.x = touch.pageX;
startPoint.y = touch.pageY;
},
handleMove(ev) {
// console.log('move',ev);
// 防止页面高度很大,出现滚动条,不能移动-默认拖动滚动条事件
ev.preventDefault();
isTouchMove = true;
var touch = ev.changedTouches[0];
var diffPonit = {}; // 存放差值
var movePonit = {
// 记录移动的距离
x: 0,
y: 0
};
diffPonit.x = touch.pageX - startPoint.x;
diffPonit.y = touch.pageY - startPoint.y;
// 移动的距离 = 差值 + 当前坐标点
movePonit.x = diffPonit.x + curPoint.x;
movePonit.y = diffPonit.y + curPoint.y;
this.move(movePonit.x, movePonit.y);
},
handleEnd(ev) {
// console.log('end', ev);
if (!isTouchMove) return;
// 更新坐标原点
var touch = ev.changedTouches[0];
curPoint.x += touch.pageX - startPoint.x;
curPoint.y += touch.pageY - startPoint.y;
// 重置
isTouchMove = false;
},
move(x, y) {
x = x || 0; // 没有传就是0
y = y || 0;
this.xMove = x;
this.yMove = y;
// translate3d (tx,ty,tz) 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px
}
}
};
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.touch {
position: fixed;
right: 20px;
bottom: 20px;
width: 45px;
height: 45px;
line-height: 45px;
text-align: center;
background-color: rgba(0, 0, 0, 0.6);
border-radius: 50%;
color: #fff;
font-size: 30px;
/* 使用transform: translate3d 处理性能高 GUP */
}
</style>

1***@qq.com
- 发布:2021-02-22 17:05
- 更新:2021-05-31 10:52
- 阅读:3201
uniapp--悬浮可拖动按钮-实现思路
分类:uni-app