How to programmatically disable page scrolling with jQuery

后端 未结 23 2351
滥情空心
滥情空心 2020-11-22 08:09

Using jQuery, I would like to disable scrolling of the body:

My idea is to:

  1. Set body{ overflow: hidden;}
  2. Capture the current
23条回答
  •  深忆病人
    2020-11-22 08:44

    I just provide a little tuning to the solution by tfe. In particular, I added some additional control to ensure that there is no shifting of the page content (aka page shift) when the scrollbar is set to hidden.

    Two Javascript functions lockScroll() and unlockScroll() can be defined, respectively, to lock and unlock the page scroll.

    function lockScroll(){
        $html = $('html'); 
        $body = $('body'); 
        var initWidth = $body.outerWidth();
        var initHeight = $body.outerHeight();
    
        var scrollPosition = [
            self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
            self.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
        ];
        $html.data('scroll-position', scrollPosition);
        $html.data('previous-overflow', $html.css('overflow'));
        $html.css('overflow', 'hidden');
        window.scrollTo(scrollPosition[0], scrollPosition[1]);   
    
        var marginR = $body.outerWidth()-initWidth;
        var marginB = $body.outerHeight()-initHeight; 
        $body.css({'margin-right': marginR,'margin-bottom': marginB});
    } 
    
    function unlockScroll(){
        $html = $('html');
        $body = $('body');
        $html.css('overflow', $html.data('previous-overflow'));
        var scrollPosition = $html.data('scroll-position');
        window.scrollTo(scrollPosition[0], scrollPosition[1]);    
    
        $body.css({'margin-right': 0, 'margin-bottom': 0});
    }
    

    where I assumed that the has no initial margin.

    Notice that, while the above solution works in most of the practical cases, it is not definitive since it needs some further customization for pages that include, for instance, an header with position:fixed. Let's go into this special case with an example. Suppose to have

    
    
    
    
    

    with

    #header{position:fixed; padding:0; margin:0; width:100%}
    

    Then, one should add the following in functions lockScroll() and unlockScroll():

    function lockScroll(){
        //Omissis   
    
    
        $('#header').css('margin-right', marginR);
    } 
    
    function unlockScroll(){
        //Omissis   
    
        $('#header').css('margin-right', 0);
    }
    

    Finally, take care of some possible initial value for the margins or paddings.

提交回复
热议问题