移动端不触发touchend的解决方法以及后续影响问题的处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了移动端不触发touchend的解决方法以及后续影响问题的处理相关的知识,希望对你有一定的参考价值。

参考技术A 在写一个下拉刷新上拉加载功能的时候使用了touch系列事件编写下拉刷新,正常的触发过程应该是:touchstart→touchmove→touchend,但是在安卓手机端,touchend是在下一次触摸的时候才会触发,百度了,原因是
主要是由于200ms超时导致内核不一定会一直处理touchmove事件,一旦超时会将后续所有的事件转交给UI处理,导致touchmove不会一直触发。
为了解决开发者需要,建议开发者在touchstart时调用event.preventDefault,这样就可以保证内核会一起触发touchmove事件了。

在touchstart中添加了event.preventDefault()方法的话,页面的点击事件和链接跳转都会失效,所以尝试在touchmove中添加event.preventDefault()方法,但是又遇到了页面无法滚动的问题,因为event.preventDefault()方法阻止了页面的滚动事件。解决这个问题就是在添加event.preventDefault()方法的时候加上判断条件,在特定条件(我这里是在页面顶端下拉的时候)下才阻止默认事件。

移动端touchstartouchmovetouchend 事件如果页面有滚动时不让触发 touchend 事件。

/*仅适用于内容中点击元素。对于拖动等元素,需要自行在页面处理。
* 主要是绑定touchstart和touchmove事件,并判断用户按下之后手指移动了多少像素。
* 如果手指移动距离小于10像素,则还是认为用户在做点击操作。如果移动距离超过了10像素,则取消后续事件监听函数的执行。*/



<script type="text/javascript"> function makeTouchableButton(ele) { if (!ele) { console.error("MIGlobals.makeTouchableButton 无效的元素!"); return false; } ele.addEventListener("touchstart", function(evt){ this.setAttribute("data-moved", "n"); var p = evt.touches[0]; this.setAttribute("data-touch-start-clientx", p.clientX); this.setAttribute("data-touch-start-clienty", p.clientY); }); ele.addEventListener("touchmove", function(evt){ if (this.getAttribute("data-moved") == "y") return false; var p = evt.touches[0]; var startClientX = parseInt(this.getAttribute("data-touch-start-clientx"), 10); var startClientY = parseInt(this.getAttribute("data-touch-start-clienty"), 10); var deltax = p.clientX - startClientX; var deltay = p.clientY - startClientY; if (Math.abs(deltax) > 10 || Math.abs(deltay) > 10) { this.setAttribute("data-moved", "y"); } }); ele.addEventListener("touchend", function(evt) { if (this.getAttribute("data-moved") == "y") { evt.stopImmediatePropagation(); return false; } }); } var divs = document.querySelector(".touchdiv"); makeTouchableButton(divs); divs.addEventListener("touchend",function(){ console.log("您点击我啦。"); }); </script>

 

以上是关于移动端不触发touchend的解决方法以及后续影响问题的处理的主要内容,如果未能解决你的问题,请参考以下文章

解决移动端页面滚动后不触发touchend事件

移动端android,长按事件时,touchend事件不触发的解决方法

移动端touchstartouchmovetouchend 事件如果页面有滚动时不让触发 touchend 事件。

如何修复移动浏览器上 touchend 事件不触发的bug

移动端常用触摸事件以及常用坐标

滑动页面时防止touch事件的误触问题