<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是行高,針對的對象是文字,height針對的是容器,
也就是高度,當height和line-height值相同時會居中,
當line-height值小於height時文字向上移動,反之向下移動。
*/
line-height: 45px; /* 文字垂直居中 */
text-align: center; /* 水平居中 */
background-color: rgba(0, 0, 0, 0.6);
border-radius: 50%;
color: #fff;
font-size: 30px;
/* 去除標簽點擊事件高亮效果 */
-webkit-tap-highlight-color: transparent;
/* 使用transform: translate3d 處理性能高 GUP */
}
</style>