How to disable rubber band in iOS web apps?

2019-01-08 09:33发布

This:

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

Works, but will disable scrolling throughout the whole page, which is far from ideal.

This:

$('*').on('touchstart', function(e){
    var element = $(this).get(0);

    if ( element.scrollTop <= 0 )                                           element.scrollTop = 1;
    if ( element.scrollTop + element.offsetHeight >= element.scrollHeight ) element.scrollTop = element.scrollHeight - element.offsetHeight - 1;
});

Works on pages that have a scrolling area. However when there is nothing to scroll it will again show the rubber-band.

So my question:

How can you disable the rubber band effect and still keep the -webkit-overflow-scrolling areas scrollable?

[Update]

Best Solution

Disable scrolling on all non-scrollable elements such as a tab bar or a navigation bar.

anElement.addEventListener('touchmove', function( event ){ event.preventDefault() };

Attach a scroll handler to the scrollable elements such as the main content.

anElement.addEventListener('touchstart', function( event ){
        if( this.scrollTop === 0 ) {
            this.scrollTop += 1;
        } else if( this.scrollTop + this.offsetHeight >= this.scrollHeight ) {
            this.scrollTop -= 1;
        }
}

7条回答
Evening l夕情丶
2楼-- · 2019-01-08 10:17

Finally I mixed some methods and these codes are the working version. But you must include the hammer.js

CSS

.scrollable{
    overflow:auto;overflow-x:hidden;-webkit-overflow-scrolling:touch;
    *{-webkit-transform:translate3d(0,0,0);}
}

JAVASCRIPT

$(document).on("touchmove",function(e){
    e.preventDefault();
});
$("body").on("touchstart",".scrollable",function(e){
    if(e.currentTarget.scrollTop===0){
        e.currentTarget.scrollTop = 1;
    }else if(e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight){
        e.currentTarget.scrollTop-=1;
    }
});
$("body").on("touchmove",".scrollable",function(e){
    e.stopPropagation();
});

$("body").hammer().on("pinch",function(e){
    e.gesture.preventDefault();
});
查看更多
登录 后发表回答