h5端可以拖拽的悬浮窗口demo
2023-11-26 本文已影响0人
泪滴在琴上
<template>
<div
class="floating-button"
:style="{
position: 'fixed',
right: buttonStyle.right,
top: buttonStyle.top,
transform: buttonStyle.transform,
}"
@touchstart="startDrag"
>
<img src="@/static/images/kefu1.png" @click="gotoAI" />
</div>
</template>
<script>
export default {
data() {
return {
buttonStyle: {
position: "fixed",
right: "2px",
top: "480px",
zIndex: 999,
},
dragging: false,
initialX: 0,
initialY: 0,
offsetX: 0,
offsetY: 0,
messageDialog: false,
};
},
methods: {
gotoAI(event) {
event.stopPropagation();
this.$router.push(`/message`);
},
startDrag(event) {
event.preventDefault(); // 阻止默认行为
this.dragging = true;
// 记录初始触摸位置
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));
// 绑定mousemove和mouseup事件
document.addEventListener("touchmove", this.onDrag, { passive: false });
document.addEventListener("touchend", this.endDrag, { passive: false });
},
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(event) {
event.preventDefault(); // 阻止事件的默认行为
event.stopPropagation(); // 阻止事件冒泡
this.dragging = false;
document.removeEventListener("touchmove", this.onDrag);
document.removeEventListener("touchend", this.endDrag);
const deltaX = event.changedTouches[0].clientX - this.initialX;
const deltaY = event.changedTouches[0].clientY - this.initialY;
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if (distance < 10) {
// 如果拖拽距离小于10,认为是点击事件
const button = document.querySelector(".floating-button img");
button.click();
}
},
},
};
</script>
<style scoped>
.floating-button {
width: 50px;
height: fit-content;
opacity: 0.9;
}
.floating-button img {
width: 100%;
height: auto;
display: block;
}
</style>