How to disable rubber band in iOS web apps?

前端 未结 8 1650
夕颜
夕颜 2020-12-01 00:50

This:

$(\'body\').on(\'touchmove\', function(e) { e.preventDefault(); });

Works, but will disable scrolling throughout the whole page, whic

8条回答
  •  感情败类
    2020-12-01 01:46

    Here's a solution that uses jQuery and Hammer.js (jquery-implementation). That's two libraries, but if you're working on mobile, chances are you'll want to include Hammer anyway.

    For every drag-event that bubbles to the top (so non-scrolling drag-interactions can use stopPropagation) the handler checks if it bubbled through any elements with class=scrolling, if so, whether the user is scrolling within the allowed boundaries of that scrollContainer and only then does it permit native scrolling.

    $("body").hammer().on('drag swipe', function(e){
    
        var scrollTarget = $(e.gesture.target).closest(".scrollable");
        if(scrollTarget.length)
        {
            var scrollTopMax = scrollTarget[0].scrollHeight - scrollTarget.outerHeight();
            if(scrollTopMax > 0){
                var scrollTop = scrollTarget.scrollTop();
                if(scrollTop > 0 && scrollTop < scrollTopMax){
                    //console.log("scrolling in the middle");
                }
                else if(scrollTop <= 0 && e.gesture.deltaY < 0){
                    //console.log("scrolling from top");
                }
                else if(scrollTop >= scrollTopMax && e.gesture.deltaY > 0){
                    //console.log("scrolling from bottom");
                }
                else{
                    //console.log("trying to scroll out of boundaries");
                    e.gesture.preventDefault();
                }
            }
            else{
                //console.log("content to short to scroll");
                e.gesture.preventDefault();
            }
        }
        else{
            //console.log("no containing element with class=scrollable");
            e.gesture.preventDefault();
        }
    });
    

    To kill drags via pinch etc.; escape as necessary to allow zooming if your view is user-scalable

    $("body").hammer().on('doubletap rotate pinch', function(e){
        e.gesture.preventDefault();
    });
    

    Tested on ios7/safari, android4.3/webview and android4.3/firefoxMobile25 and the only solution that didn't break.

提交回复
热议问题