HTML `dialog` element: scroll content independently of background

前端 未结 3 746
南旧
南旧 2021-01-21 18:33

I am trying to use the dialog element.

When the dialog/modal is closed, the body should be scrollable.

When the dialog/modal is open, if it has larg

3条回答
  •  长发绾君心
    2021-01-21 18:50

    Update

    I created another example where your main content is not scrolled with your modal if it is larger than your main content. You can set position to fixed on your container to achieve this.

    (function() {
      var openBtn = document.getElementById('open-dialog');
      var myDialog = document.getElementById('my-dialog');
    
      openBtn.addEventListener('click', function() {
        if (typeof myDialog.showModal === "function") {
          myDialog.showModal();
        } else {
          alert("Dialog API not supported by browser");
        }
      });
    
    })();
    #container {
      height: 100vh;
      width: 100vw;
      position: fixed;
      top: 0;
      left: 0;
      background: #ccc;
    }
    
    #my-dialog {
      margin-top: 1rem;
      margin-bottom: 3rem;
      top: 3rem;
      width: 50%;
      overflow-y: auto;
    }
    
    #my-dialog__content {
      display: flex;
      flex-direction: column;
      height: 200vh;
    }
    
    menu {
      width: 100%;
      padding: 0;
      margin: 0 auto;
    }
    
    #cancel-button {
      width: 100%
    }

    Original answer

    You can set a max-height on your dialog and style the contents of your dialog accordingly. See example below.

    (function() {
      var openBtn = document.getElementById('open-dialog');
      var myDialog = document.getElementById('my-dialog');
    
      openBtn.addEventListener('click', function() {
        if (typeof myDialog.showModal === "function") {
          myDialog.showModal();
        } else {
          alert("Dialog API not supported by browser");
        }
      });
    
    })();
    #my-dialog {
      width: 50%;
      max-height: 50vh;
      overflow-y: auto;
    }
    
    #my-dialog__content {
      display: flex;
      flex-direction: column;
      height: 150vh;
    }
    
    menu {
      width: 100%;
      padding: 0;
      margin: 0 auto;
    }
    
    #cancel-button {
      width: 100%
    }

提交回复
热议问题