<div class="floating-button"
:style="{ position: 'fixed', right: buttonStyle.right, top: buttonStyle.top, transform: buttonStyle.transform }"
@touchstart="startDrag" @touchmove="onDrag" @touchend="endDrag" @touchcancel="endDrag">
</div>
data() {
return {
buttonStyle: {
position: "fixed",
right: "20px",
top: "300px",
zIndex: 999,
},
}
}
methods: {
startDrag(event) {
event.preventDefault(); // 阻止默认行为
this.dragging = true;
console.log(event)
// 记录初始触摸位置
this.initialX = event.touches[0].clientX;
this.initialY = event.touches[0].clientY;
// 记录当前偏移量
this.offsetX = parseInt(this.buttonStyle.right.slice(0, -2));
this.offsetY = parseInt(this.buttonStyle.top.slice(0, -2));
},
onDrag(event) {
event.preventDefault(); // 阻止默认行为
if (this.dragging) {
// 计算偏移量
const deltaX = event.touches[0].clientX - this.initialX;
const deltaY = event.touches[0].clientY - this.initialY;
// 更新按钮位置
this.buttonStyle.right = `${this.offsetX - deltaX}px`;
this.buttonStyle.top = `${this.offsetY + deltaY}px`;
}
},
endDrag() {
this.dragging = false;
},
}
.floating-button {
width: 80rpx;
height: 80rpx;
background: green;
}
网友评论