在 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 的框架或平台。
网友回复
- threejs如何做个三维搭积木的游戏?
- three如何实现标记多个起始路过地点位置后选择旅行工具(飞机汽车高铁等),最后三维模拟行驶动画导出mp4?
- ai实时驱动的3d数字人可视频聊天的开源技术有吗
- swoole+phpfpm如何实现不同域名指向不同目录的多租户模式?
- 如何用go替换nginx实现请求phpfpm解析运行php脚本?
- 有没有浏览器离线运行进行各种文档、图片、视频格式转换的开源工具?
- 如何使用go语言搭建一个web防火墙?
- linux如何检测特定网络协议比如http协议中报文是否包含特点关键词并阻止返回给客户?
- 如果在nginx外过滤包含某些关键词的网页并阻止打开?
- 程序员怎么做副业赚钱?



 
				 
			 
			 
				 
			