How to programmatically disable page scrolling with jQuery

后端 未结 23 2500
滥情空心
滥情空心 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:36

    For folks who have centered layouts (via margin:0 auto;), here's a mash-up of the position:fixed solution along with @tfe's proposed solution.

    Use this solution if you're experiencing page-snapping (due to the scrollbar showing/hiding).

    // lock scroll position, but retain settings for later
    var scrollPosition = [
        window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
        window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
    ];
    var $html = $('html'); // bow to the demon known as MSIE(v7)
    $html.addClass('modal-noscroll');
    $html.data('scroll-position', scrollPosition);
    $html.data('margin-top', $html.css('margin-top'));
    $html.css('margin-top', -1 * scrollPosition[1]);
    

    …combined with…

    // un-lock scroll position
    var $html = $('html').removeClass('modal-noscroll');
    var scrollPosition = $html.data('scroll-position');
    var marginTop = $html.data('margin-top');
    $html.css('margin-top', marginTop);
    window.scrollTo(scrollPosition[0], scrollPosition[1])
    

    …and finally, the CSS for .modal-noscroll

    .modal-noscroll
    {
        position: fixed;
        overflow-y: scroll;
        width: 100%;
    }
    

    I would venture to say this is more of a proper fix than any of the other solutions out there, but I haven't tested it that thoroughly yet… :P


    Edit: please note that I have no clue how badly this might perform (read: blow up) on a touch device.

提交回复
热议问题