force-stop momentum scrolling on iphone/ipad in javascript

元气小坏坏 提交于 2020-01-01 08:46:20

问题


Is it possible to force-stop momentum scrolling on iphone/ipad in javascript?

Extra: pretty sure this is pie in the sky, but for bonuspoints (honor and kudos), after dom-manipulation and a scrollTo applied, resume scroll with the same momentum before the forced stop. How to?


回答1:


This is actually very possible when using fastclick.js. The lib removes the 300ms click delay on mobile devices and enables event capturing during inertia/momentum scrolling.

After including fastclick and attaching it to the body element, my code to stop scrolling and go to the top looks like this:

scrollElement.style.overflow = 'hidden';
scrollElement.scrollTop = 0;
setTimeout(function() {
  scrollElement.style.overflow = '';
}, 10);

The trick is to set overflow: hidden, which stops the inertia/momentum scrolling. Please see my fiddle for a full implementation of stop scrolling during inertia/momentum.




回答2:


Here is my code using jQuery animation (running as onclick event)

var obj=$('html, body'); // your element

if(!obj.is(':animated')) {

    obj.css('overflow', 'hidden').animate({ scrollTop: 0 }, function(){ obj.css('overflow', ''); });

}

Tested on iPhone 6




回答3:


I have found a way to CANCEL the BODY momentum scrolling by assigning the html.scrollTop property on touchend event. Looks like this:

let html = document.querySelector('html');
window.addEventListener( 'touchend', function( e ){
    html.scrollTop = html.scrollTop;
});

Tested on iOS 13

UPD: The above solution fails on iOS 12, because the actual scrolling element is not "html" in this version.

The below code works for Both 12 & 13:

window.addEventListener( 'touchend', function( e ){
    window.scroll( 0, window.scrollY );
});


来源:https://stackoverflow.com/questions/16109561/force-stop-momentum-scrolling-on-iphone-ipad-in-javascript

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