1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| <template> <view class="drag-container"> <view class="drag-item" :style="itemStyle" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" > 拖拽我 </view> </view> </template>
<script> export default { data() { return { startX: 0, startY: 0, moveX: 0, moveY: 0, isDragging: false } }, computed: { itemStyle() { if (!this.isDragging) { return { transform: `translate3d(${this.moveX}px, ${this.moveY}px, 0)`, transition: 'transform 0.3s' } } return { transform: `translate3d(${this.moveX}px, ${this.moveY}px, 0)` } } }, methods: { handleTouchStart(e) { const touch = e.touches[0] this.startX = touch.clientX - this.moveX this.startY = touch.clientY - this.moveY this.isDragging = true }, handleTouchMove(e) { const touch = e.touches[0] this.moveX = touch.clientX - this.startX this.moveY = touch.clientY - this.startY // 防止页面滚动 e.preventDefault() }, handleTouchEnd() { this.isDragging = false // 判断是否超出边界,如果是则回弹 const maxX = this.containerWidth - this.itemWidth const maxY = this.containerHeight - this.itemHeight if (this.moveX < 0) this.moveX = 0 if (this.moveY < 0) this.moveY = 0 if (this.moveX > maxX) this.moveX = maxX if (this.moveY > maxY) this.moveY = maxY } } } </script>
<style lang="scss"> .drag-container { position: relative; width: 100%; height: 500rpx; background: #f5f5f5; }
.drag-item { position: absolute; width: 200rpx; height: 200rpx; background: #409eff; color: #fff; display: flex; align-items: center; justify-content: center; user-select: none; } </style>
|