在uni-app中,可以通过使用touch事件监听用户的触摸行为来实现拖动功能。
<template>
<view class="container">
<view
class="draggable"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{left: x + 'px', top: y + 'px'}"
>
按下拖动
</view>
</view>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0,
startX: 0,
startY: 0
}
},
methods: {
handleTouchStart(event){
// 获取触摸点信息
const touch = event.touches[0];
// 触摸时重置起始位置
this.startX = touch.clientX;
this.startY = touch.clientY;
},
handleTouchMove(event) {
// 获取触摸点信息
const touch = event.touches[0];
// 计算移动后的位置
this.x += touch.clientX - this.startX;
this.y += touch.clientY - this.startY;
// 更新起始位置
this.startX = touch.clientX;
this.startY = touch.clientY;
},
handleTouchEnd(event){}
}
}
</script>
<style>
.container {
position: relative;
height: 100%;
}
.draggable {
position: absolute;
width: 100px;
height: 100px;
background-color: #f0f0f0;
text-align: center;
line-height: 100px;
user-select: none;
}
</style>