用在移动端触摸屏幕上的盒子滑动,这里用在返回按钮
html部分
<div class="backBtn"
:style="'backgroundColor:'+style.bGColor"
ref="draggableButton"
@touchstart="startDrag"
@touchmove="doDrag"
@touchend="stopDrag"
style="position: absolute; left: 20px; top: 12vh;"
@click="back"
>
<span>返回</span>
</div>
js部分
// 监测触摸开始
startDrag(event) {
this.dragging = true
// 阻止默认事件和冒泡
event.preventDefault()
// 记录初始位置
this.startX = event.touches[0].clientX
this.startY = event.touches[0].clientY
// 计算触摸点与元素左上角的偏移量
const rect = this.$refs.draggableButton.getBoundingClientRect()
this.offsetX = event.touches[0].clientX - rect.left
this.offsetY = event.touches[0].clientY - rect.top
// 添加移动和结束监听
document.addEventListener('touchmove', this.doDrag, { passive: false })
document.addEventListener('touchend', this.stopDrag)
},
doDrag(event) {
if (this.dragging) {
// 计算新位置
const newX = event.touches[0].clientX - this.offsetX
const newY = event.touches[0].clientY - this.offsetY
// 更新按钮位置
this.$refs.draggableButton.style.left = `${newX}px`
this.$refs.draggableButton.style.top = `${newY}px`
}
},
// 触摸移动结束
stopDrag() {
this.dragging = false
// 移除事件监听器
document.removeEventListener('touchmove', this.doDrag, { passive: false })
document.removeEventListener('touchend', this.stopDrag)
// 检查是否发生了拖动 主要用于click点击事件生效(解决添加了触摸事件后click事件识别不到)
// 你可以根据需要设置一个阈值来判断是否发生了“显著的”拖动
const threshold = 5 // 像素阈值
const dx = Math.abs(event.changedTouches[0].clientX - this.startX)
const dy = Math.abs(event.changedTouches[0].clientY - this.startY)
if (dx < threshold && dy < threshold) {
// 没有发生显著的拖动,可以视为点击
this.back() // 调用点击逻辑
}
}
// 盒子上的点击事件
back() {
this.clickStu = {}
},
css部分
.backBtn {
width: 50px;
//height: 22px;
font-size: 22px;
//margin: 0 10px 5px;
display: flex;
align-items: center;
height: 50px;
border-radius: 50%;
text-align: center;
color: #ffffff;
background-color: #f1afaf;
justify-content: center;
cursor: grab;
user-select: none; /* 防止选择文本 */
transition: transform 0.1s ease;
z-index: 999999;
span {
font-size: 14px;
//margin-left: 10px;
}
}