How to programmatically disable page scrolling with jQuery

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

    Not sure if anybody has tried out my solution. This one works on the whole body/html but no doubt it can be applied to any element that fires a scroll event.

    Just set and unset scrollLock as you need.

    var scrollLock = false;
    var scrollMem = {left: 0, top: 0};
    
    $(window).scroll(function(){
        if (scrollLock) {
            window.scrollTo(scrollMem.left, scrollMem.top);
        } else {
            scrollMem = {
                left: self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
                top: self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
            };
        }
    });
    

    Here's the example JSFiddle

    Hope this one helps somebody.

提交回复
热议问题