vue2 实现代码
<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>
export default {
data() {
return {
top: 20, // 初始位置的上边距
left: 20, // 初始位置的左边距
isDragging: false,
touchStartX: 0,
touchStartY: 0,
};
},
methods: {
startDrag(event) {
this.isDragging = true;
const touch = event.touches[0];
this.touchStartX = touch.clientX - this.left;
this.touchStartY = touch.clientY - this.top;
},
drag(event) {
if (this.isDragging) {
const touch = event.touches[0];
const newLeft = touch.clientX - this.touchStartX;
const newTop = touch.clientY - this.touchStartY;
// 边界检查,确保不超出屏幕左右和上下边界
const maxX = window.innerWidth - 10 - this.$el.offsetWidth; // 10px为边界距离
const minX = 10; // 10px为边界距离
const maxY = window.innerHeight - 10 - this.$el.offsetHeight; // 10px为边界距离
const minY = 10; // 10px为边界距离
this.left = Math.min(Math.max(newLeft, minX), maxX);
this.top = Math.min(Math.max(newTop, minY), maxY);
}
},
stopDrag() {
this.isDragging = false;
},
},
};
</script>
<style scoped>
.customer-service-button {
position: fixed;
z-index: 1000;
cursor: pointer;
}
img{
width: 50px;
height: 50px;
}
</style>
vue3实现代码
<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>