模态打开时如何防止身体滚动

Itarachiu

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

伊恩·韦勒森

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

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

我为你做了最后的选择。

// 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
  }
}

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章