如何解决Android设备上touchend无法触发问题
移动项目开发过程中,经常需要用到滑动的事件来处理一些效果。通常情况下,我们会通过 touchstart->touchmove->touchend 的过程来定义这个事件。这些事件的触发顺序是 touchstart, touchmove, touchmove ….. touchend 。绝大部分平板或手机也正如我们想象的那样有序执行着。但是以 Android 4.0.4 为首的一些可恶分子却有些不听话:他们的 touchend 事件没有如预期的那样触发。
监听这些事件我们会发现,当只是轻点一下屏幕时,touchend 可以正常触发。但是只要当 touchmove 被触发之后,touchend 就不会再被触发了,而且 touchmove 也没有持续触发。
在网上搜集了一些资料显示,这是 Android 上浏览器的 bug
On Android ICS if no preventDefault is called on touchstart or the firsttouchmove,
further touchmove events and the touchend will not be fired.
正如提到的我们只需要在 touchstart 或者 touchmove 里执行一下 e.preventDefault(); 就可以避免这个 bug。但是,问题来了:添加了 preventDefault 之后,正常的 scroll 事件也被屏蔽了!我们意外的发现滚动条也不能用了!
于是,我们开始尝试各种添加 preventDefault 事件的时机:闭包,延迟,判断等一一用上。最终焦点落在了 firsttouchmove 上,于是有了以下代码。
1 | var touchY = 0; |
基本上主要的思想就是在 touchmove 的时候判断出纵轴的位移量,当小于某个值的时候就认为是在执行左右滑动,且需要执行 preventDefault 来确保 touchend 可以正常触发。
如何解决Android设备上touchend无法触发问题
https://blog.catooilg.com/2020/08/03/yuque/如何解决Android设备上touchend无法触发问题/