在 uniapp 中,touchstart 事件后,如果用户的手指移出目标元素,再松开时无法触发 touchend,这是因为触摸事件绑定在具体的元素上,而当手指移出该元素时,触摸事件就会失效,无法触发 touchend。要解决这个问题,可以通过以下几种方法来确保在手指移出目标元素时仍能捕捉到 touchend 事件。
解决方法:1. 绑定全局事件监听将 touchend 事件绑定到全局对象 document 或 window 上,而不是特定的元素上。这种方式可以确保手指无论在哪里松开,都能捕捉到 touchend 事件。
// 在页面的 onLoad 或 mounted 中绑定事件监听
onLoad() {
document.addEventListener('touchend', this.handleTouchEnd);
},
methods: {
handleTouchEnd(e) {
// 处理 touchend 逻辑
console.log('触发了touchend');
},
handleTouchStart(e) {
console.log('触发了touchstart');
// 处理 touchstart 逻辑
}
},
// 别忘了在 onUnload 或页面卸载时移除事件监听
onUnload() {
document.removeEventListener('touchend', this.handleTouchEnd);
} 通过这种方法,即使用户将手指移动到目标元素之外,也能够触发 touchend 事件。
2. 使用 touchcancel 事件在 uniapp 中,还有一个与 touchend 类似的事件叫做 touchcancel,当手指移出元素或者被系统中断(例如电话、其他应用程序打断)时会触发。可以同时监听 touchend 和 touchcancel 事件来更好地覆盖不同场景。
methods: {
handleTouchStart(e) {
console.log('触发了touchstart');
// 处理 touchstart 逻辑
},
handleTouchEnd(e) {
console.log('触发了touchend');
// 处理 touchend 逻辑
},
handleTouchCancel(e) {
console.log('触发了touchcancel');
// 处理 touchcancel 逻辑
}
},
onLoad() {
document.addEventListener('touchend', this.handleTouchEnd);
document.addEventListener('touchcancel', this.handleTouchCancel);
},
onUnload() {
document.removeEventListener('touchend', this.handleTouchEnd);
document.removeEventListener('touchcancel', this.handleTouchCancel);
} 3. 监听整个页面的 touchmove 事件如果需要在 touchstart 后持续跟踪手指的移动情况,可以监听全局的 touchmove 事件,当手指移动超出元素范围时,可以手动触发 touchend 逻辑:
methods: {
handleTouchStart(e) {
console.log('触发了touchstart');
// 监听全局 touchmove
document.addEventListener('touchmove', this.handleTouchMove);
},
handleTouchMove(e) {
// 检测手指是否移出目标区域
console.log('手指正在移动');
// 如果需要,可以手动触发 touchend 逻辑
},
handleTouchEnd(e) {
console.log('触发了touchend');
// 移除 touchmove 监听器
document.removeEventListener('touchmove', this.handleTouchMove);
}
},
onLoad() {
document.addEventListener('touchend', this.handleTouchEnd);
},
onUnload() {
document.removeEventListener('touchend', this.handleTouchEnd);
document.removeEventListener('touchmove', this.handleTouchMove);
} 总结要解决 touchstart 后手指移出目标元素无法触发 touchend 的问题,可以通过全局事件监听或者额外监听 touchcancel 来捕获所有触摸事件。这个方法不仅适用于 uniapp,也适用于其他基于 Web 的框架或平台。
网友回复
视频大模型和最强文本大模型通过代码生成视频哪个性价比更高?
seedream5.5为啥无法将图白色背景修改成透明?
seedance2如何通过2张不同角度平视图来识别场景进行人物定位?
有没有免费的浏览器中离线运行的语音识别ai模型?
微信小程序个人版不交钱认证就不让你用二维码,报错"errcode":85411?
美丽国为啥要限制ai发展?
seedance2如何参考白模视频使用真实场景和人物生成新视频?
如何设定小孩看电视的时候每隔10分钟弹出一个题目,答对才能继续,答错继续下一题?
直播数字人根据公屏互动评论实时做出不用动作技术是什么?
未来ai文本大模型根据剧本直接生成像素风或三维白模或灰模粗糙场景动画html给视频大模型参考站位与运镜?


