【问题标题】:How to prevent body scrolling while modal is open如何在模态打开时防止正文滚动
【发布时间】:2022-01-02 20:18:34
【问题描述】:

我正在使用W3schools modal script,我想添加防止模型打开时整个身体滚动的功能。我根据我的需要对原始脚本做了一些小的修改,我为模态框添加了一个高度和一个溢出的滚动条。如何在模式处于活动状态时防止正文滚动条工作?

【问题讨论】:

    标签: html css


    【解决方案1】:

    最简单的方法是改变body属性。 当模态框打开时,将高度设置为 100% 并隐藏溢出。当模态关闭时,更改属性做初始值(自动)。

    您可以使用 css 类进行此操作,因此当打开模式时,您可以使用此属性将类设置为主体,然后在关闭模式时删除该类。或者你可以使用 javascript 来制作,并手动设置 body 的样式。

    我为你做了最后一条路。

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
        modal.style.display = "block";
        document.body.style.overflow = "hidden"; // ADD THIS LINE
        document.body.style.height = "100%"; // ADD THIS LINE
    }
    
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
      modal.style.display = "none";
        document.body.style.overflow = "auto"; // ADD THIS LINE
        document.body.style.height = "auto"; // ADD THIS LINE
    }
    
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
        document.body.style.overflow = "auto"; // ADD THIS LINE
        document.body.style.height = "auto";  // ADD THIS LINE
      }
    }
    

    带有“ADD THIS LINE”注释的行是您需要在代码中添加的行。

    当然,您可以将 css 样式放在一个类中,然后使用 javascript 或 jquery 添加或删除该类。

    【讨论】:

    • 我知道这是一个旧答案,但是是的,这是可行的。问题是由于隐藏了溢出,页面会自动转到最顶部。你有解决办法吗?
    • 你明白了吗?
    【解决方案2】:

    打开模态时将document.body.style.overflow设置为hidden,关闭模态时设置为scroll

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 2014-01-01
      • 2019-04-16
      • 1970-01-01
      • 2016-05-03
      • 2019-10-17
      • 2012-03-21
      • 2018-04-01
      相关资源
      最近更新 更多