<template>
<div
class="customer-service-button"
:style="{ top: top + 'px', left: left + 'px' }"
@touchstart="startDrag"
@touchmove="drag"
@touchend="stopDrag"
>
<!-- 这里可以放客服按钮的图标或文本 -->
<img src="../assets/logo.png" alt="客服">
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const top = ref(20); // 初始位置的上边距
const left = ref(20); // 初始位置的左边距
let isDragging = false;
let touchStartX = 0;
let touchStartY = 0;
const startDrag = (event) => {
isDragging = true;
const touch = event.touches[0];
touchStartX = touch.clientX - left.value;
touchStartY = touch.clientY - top.value;
};
const drag = (event) => {
if (isDragging) {
const touch = event.touches[0];
const newLeft = touch.clientX - touchStartX;
const newTop = touch.clientY - touchStartY;
// 边界检查,确保不超出屏幕左右和上下边界
const maxX = window.innerWidth - 10 - event.target.offsetWidth; // 10px为边界距离
const minX = 10; // 10px为边界距离
const maxY = window.innerHeight - 10 - event.target.offsetHeight; // 10px为边界距离
const minY = 10; // 10px为边界距离
left.value = Math.min(Math.max(newLeft, minX), maxX);
top.value = Math.min(Math.max(newTop, minY), maxY);
}
};
const stopDrag = () => {
isDragging = false;
};
return {
top,
left,
startDrag,
drag,
stopDrag,
};
},
};
</script>
<style scoped>
.customer-service-button {
position: fixed;
z-index: 1000;
cursor: pointer;
}
img{
width: 50px;
height: 50px;
}
</style>
实现自定义拖动客服按钮
最新推荐文章于 2024-08-27 15:16:52 发布