在 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 的框架或平台。
网友回复
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?
linux上如何运行任意windows程序?
ai能写出比黑客还厉害的零日漏洞等攻击工具攻击任意软件系统工程?
js如何获取浏览器的音频上下文指纹、Canvas指纹、WebGL渲染特征?
为啥ai开始抛弃markdown文本,重新偏好html文本了?
网站有没有办法鉴别访问请求是由ai操控chrome-devtools-mcp发出的?


