detect if a touchstart/touchend has cancelled a scroll (momentum scroll)

穿精又带淫゛_ 提交于 2019-12-09 21:25:01

问题


i listen for touchstart and touchend events to make my app more responsive for mobile.

the problem is, if you 'flick scroll' (the page is still scrolling even after finger has left screen), and then stop the scroll with a tap - if there is an event on touchend attached to the element you tapped, it will fire.

I need a way to detect if the touchstart or touchend has stopped a scroll, so i can stop any events firing.

I tried setting a variable on scroll (i noticed scroll event on mobile only fires after scroll has finished, i.e page has stopped even on momentum scrolling):

$(window).scroll(function(){
    cancelled_scrolling = true;
    setTimeout(function(){
        cancelled_scrolling = false;
    },200);
});

however, when i tap it seems the touchend fires before the .scroll() event, as this doesn't work:

$('body').on('touchend', function(){

    if(cancelled_scrolling){
        alert('ahahahah');
        return false;
    }

    //code to trigger events depending on event.target after here
});

how can I achieve this?

EDIT:

found an answer to this -

step1 - save the scrollTop on touchend step2 - on touchstart, check the saved scrollTop against a new scrollTop

  • if they don't match, the page was scrolled even after the touchend event occurred

回答1:


On touchStart, keep track of the scrollTop and scrollLeft for each parent node. On touchMove, check if any of these values have changed. If so, cancel the touch. This is slightly better than just checking on touchEnd because maybe they scrolled the page and then unscrolled.

You can also see this logic implemented here: https://github.com/JedWatson/react-tappable/blob/cf755ea0ba4e90dfa6ac970316ff7c35633062bd/src/TappableMixin.js#L120



来源:https://stackoverflow.com/questions/27040241/detect-if-a-touchstart-touchend-has-cancelled-a-scroll-momentum-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!