js/css : disable scrollbar but keep scroll position

后端 未结 6 432
情深已故
情深已故 2020-12-31 01:40

I\'m using the Jquery dialog to open a popup box window on top of a page. When I open the dialog box, I want the general page scrolling to be disabled. To do so, I am doing

6条回答
  •  伪装坚强ぢ
    2020-12-31 01:59

    I use these two functions for the same purpose:

    function enableBodyScroll() {
      if (document.readyState === 'complete') {
        document.body.style.position = '';
        document.body.style.overflowY = '';
    
        if (document.body.style.marginTop) {
          const scrollTop = -parseInt(document.body.style.marginTop, 10);
          document.body.style.marginTop = '';
          window.scrollTo(window.pageXOffset, scrollTop);
        }
      } else {
        window.addEventListener('load', enableBodyScroll);
      }
    }
    
    function disableBodyScroll({ savePosition = false } = {}) {
      if (document.readyState === 'complete') {
        if (document.body.scrollHeight > window.innerHeight) {
          if (savePosition) document.body.style.marginTop = `-${window.pageYOffset}px`;
          document.body.style.position = 'fixed';
          document.body.style.overflowY = 'scroll';
        }
      } else {
        window.addEventListener('load', () => disableBodyScroll({ savePosition }));
      }
    }
    

    How it works:

    1. When you want to disable the scroll with saving the current position, you run disableBodyScroll({ savePosition: true }).

    2. The function check whether the page loaded or not (because user may trigger dialog opening during the loading).

    3. If the page is loaded, it saves current scroll position by setting margin-top on body, then it sets position: fixed; overflow-y: scroll on it to remove scrollbar.

    4. If the page isn't loaded, it adds event listener to run (3.) when the page loads.

    For enabling scroll everything is the same, but the function remove styles instead of setting them.

    Source of the code: https://github.com/funbox/diamonds/blob/master/lib/body-scroll.ts

提交回复
热议问题