
小程序元素拖拽
你可以在小程序中使用拖动事件来实现某个元素的拖拽功能。
步骤如下:
- 在 .wxml 文件中定义要拖拽的元素。
- 在 .js 文件中监听 touchstart、touchmove 和 touchend 事件。
- 在 touchstart 事件处理程序中,记录元素的初始位置。
- 在 touchmove 事件处理程序中,计算元素的位移并更新其位置。
- 在 touchend 事件处理程序中,释放元素。
示例代码:
拖拽我
Page({
data: {
startX: 0,
startY: 0,
moveX: 0,
moveY: 0,
},
touchstart(e) {
const { pageX, pageY } = e.touches[0]
this.setData({
startX: pageX,
startY: pageY,
moveX: this.data.moveX,
moveY: this.data.moveY,
})
},
touchmove(e) {
const { pageX, pageY } = e.touches[0]
const { startX, startY, moveX, moveY } = this.data
const offsetX = pageX - startX + moveX
const offsetY = pageY - startY + moveY
this.setData({
moveX: offsetX,
moveY: offsetY,
})
},
touchend() {
this.setData({
moveX: 0,
moveY: 0,
})
},
})










