How to scroll the page when a modal dialog is longer than the screen?

前端 未结 11 519
时光取名叫无心
时光取名叫无心 2020-12-22 20:42

I have a modal dialog in my app which can get quite long in the y direction. This introduces a problem whereby some of the content of the dialog is hidden off the bottom of

11条回答
  •  半阙折子戏
    2020-12-22 21:15

    This is what fixed it for me:

    max-height: 100%;
    overflow-y: auto;
    

    EDIT: I now use the same method currently used on Twitter where the modal acts sort of like a separate page on top of the current content and the content behind the modal does not move as you scroll.

    In essence it is this:

    var scrollBarWidth = window.innerWidth - document.body.offsetWidth;
    $('body').css({
      marginRight: scrollBarWidth,
      overflow: 'hidden'
    });
    $modal.show();
    

    With this CSS on the modal:

    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    

    JSFiddle: https://jsfiddle.net/0x0049/koodkcng/
    Pure JS version (IE9+): https://jsfiddle.net/0x0049/koodkcng/1/

    This works no matter the height or width of the page or modal dialog, allows scrolling no matter where your mouse/finger is, doesn't have the jarring jump some solutions have that disable scroll on the main content, and looks great too.

提交回复
热议问题