Detect if element has stopped momentum scrolling?

谁都会走 提交于 2019-12-01 03:55:09
dagge

You can calculate a swipe velocity and try to figure out if momentum scroll will occur based on some threshold value. I've done some testing and about 0.25 pixels/ms seems to be a good value.

Note: Sometimes momentum scrolling will occur for lower velocities too. The lowest velocity to cause momentum scrolling that I recorded was 0.13 (with very short delta time) so if you need a 100% perfect solution, keep on looking.

The example code also detects and deals with overscrolling.

Using JQuery;

var scrollWrapper = $('#myWrapper');
var starTime, startScroll, waitForScrollEvent;
scrollWrapper.bind('touchstart', function() {
   waitForScrollEvent = false;
});

scrollWrapper.bind('touchmove', function() { 
  startTime = new Date().getTime(); startScroll = scrollWrapper.scrollTop();
});

scrollWrapper.bind('touchend', function() {
  var deltaTime = new Date().getTime() - startTime;
  var deltaScroll = Math.abs(startScroll - scrollWrapper.scrollTop());
  if (deltaScroll/deltaTime>0.25 
        || scrollWrapper.scrollTop()<0 
        || scrollWrapper.scrollTop()>scrollWrapper.height()) {
    // will cause momentum scroll, wait for 'scroll' event
    waitForScrollEvent = true;
  }
  else {
    onScrollCompleted(); // assume no momentum scroll was initiated
  }
  startTime = 0;
});

scrollWrapper.bind('scroll', function() {
  if (waitForScrollEvent) {
    onScrollCompleted();
  }
});

In my case this worked perfectly:

var timer;
$(scrollWrapper).on('scroll',function(e){
    if(timer){
        clearTimeout(timer);
    }
    timer = setTimeout(function(){
       $(this).trigger('scrollFinished');
    }, 55)
})



 $(scrollWrapper).on('scrollFinished',function(){
         // will be called when momentum scroll is finished
   })

Publish 'scrollfinished' event when scroll has stopped.

You could also add a function that recursivly calls itself until the scrolling has stopped within the element and then call futher function from there.

isScrolling() {
  var scrollStart = <element>.scrollTop;
  setTimeout(function() {
    var scrollPos = <element>.scrollTop;
    if (scrollStart !== scrollPos) {
      this.isScrolling()
    } else {
      // Scrolling has stopped
    }
  }, 100)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!