<template>
<view class="container">
<view class="draggable"
@touchmove.stop.prevent="moveHandle"
@touchmove="handleTouchMove" @touchstart="handleTouchStart"
@touchend="handleTouchEnd"
:style="{transform: 'translate(' + offset.x + 'px, ' + offset.y + 'px)'}">
拖动我
</view>
</view>
</template>
<script>
export default {
data() {
return {
offset: { x: 0, y: 0 },
startPoint: { x: 0, y: 0 }
};
},
methods: {
handleTouchStart(event) {
this.startPoint = { x: event.touches[0].clientX, y: event.touches[0].clientY };
},
handleTouchMove(event) {
const currentPoint = { x: event.touches[0].clientX, y: event.touches[0].clientY };
const delta = {
x: currentPoint.x - this.startPoint.x,
y: currentPoint.y - this.startPoint.y
};
this.offset = { x: this.offset.x + delta.x, y: this.offset.y + delta.y };
this.startPoint = currentPoint;
// 限制拖动范围
this.restrictDrag();
},
handleTouchEnd() {
// 可以在这里处理拖动结束后的逻辑
},
//获取父元素宽度高度使其防止拖出页面
restrictDrag() {
uni.createSelectorQuery()
.select('.container') // 选择你要获取尺寸的盒子元素,这里假设盒子元素的class为box
.boundingClientRect((res) => {
const maxX = res.width - 98; // 屏幕宽度,单位为px
// console.log('宽度111', res)
const maxY = res.height - 98; // 屏幕高度,单位为px
const minX = 0; // 边距
const minY = 0; // 边距
// console.log('宽度', this.offset.x, '-----', maxX)
// console.log('高度', this.offset.y, '-----', maxY)
if (this.offset.x > maxX) {
this.offset.x = maxX;
} else if (this.offset.x < minX) {
this.offset.x = minX;
}
if (this.offset.y > maxY) {
this.offset.y = maxY;
} else if (this.offset.y < minY) {
this.offset.y = minY;
}
})
.exec();
},
//阻止其他元素触摸
moveHandle() {
return false;
},
}
};
</script>
<style>
.container {
overflow: hidden;
position: relative;
}
.draggable {
width: 100px;
height: 100px;
background-color: #f0f0f0;
position: absolute;
cursor: move;
user-select: none;
}
</style>
uniapp触摸拖动元素改变位置
于 2024-04-24 15:31:11 首次发布