仅在模态为开放式IOS时如何禁用正文滚动

Ben*_*ngy 4 html css bootstrap-modal twitter-bootstrap-3

仅iOS / iPhone X / iPhone 7等

甚至jQuery模式库也不起作用!https://jquerymodal.com/-在iPhone上打开模态,您将能够滚动主体。

我发现很难找到一种在每次打开模态时都不会使页面跳到顶部而停止主体滚动的解决方案(这与页面滚动一样糟糕)

看来这是一个很大的问题,许多人都在经历。如您所见:

我没有运气就上网了,有人可以解决吗?

daG*_*GUY 9

我创建了以下解决方案,该解决方案可在iOS 12上使用!

尽管下面的嵌入式演示使用了Bootstrap 4,但是相同的解决方案在Bootstrap 3中同样有效,因为模式类或事件名称都没有不同。

第1步:body打开模态时,使用固定位置冻结到位

当打开Bootstrap模态时,将一个名为的类.modal-open添加到body。将以下其他样式添加到此类:

body {
    &.modal-open {
        bottom: 0;
        left: 0;
        position: fixed;
        right: 0;
        top: 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,每当打开模态时,body它将固定在适当的位置,并调整为与视口本身相同的尺寸。这完全阻止了滚动,因为无处可滚动!

但是:这也意味着打开模式会导致页面跳到顶部,因为该页面body不再延伸超过视口的底部边缘(假定页面内容更高)。

步骤2:在模式打开时模拟上一个滚动距离

Bootstrap公开了在打开或关闭模式时触发的事件。我们可以使用这些方法通过在打开模式时将顶部body 向上拉来解决“跳至顶部”问题,从而使滚动位置看起来没有改变:

$(function() {
    var $window = $(window),
        $body = $("body"),
        $modal = $(".modal"),
        scrollDistance = 0;

    $modal.on("show.bs.modal", function() {
        // Get the scroll distance at the time the modal was opened
        scrollDistance = $window.scrollTop();

        // Pull the top of the body up by that amount
        $body.css("top", scrollDistance * -1);
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,关闭模式时页面仍将跳至顶部,因为的scrollTopwindow仍然为0

步骤3:关闭模态时重置所有内容

现在,我们只需要挂起在模式关闭时触发的事件,并将一切恢复原状:

  • 删除固定位置和负的顶值 body
  • 将窗口的滚动位置设置回原来的位置
$modal.on("hidden.bs.modal", function() {
    // Remove the negative top value on the body
    $body.css("top", "");

    // Set the window's scroll position back to what it was before the modal was opened
    $window.scrollTop(scrollDistance);  
});
Run Code Online (Sandbox Code Playgroud)

无需手动删除上的固定位置body,因为这是通过.modal-open类设置的,Bootstrap在模式关闭时会删除该类。


演示版

放在一起,现在您可以防止打开模态时在iOS上进行后台滚动而不会丢失滚动位置!

在iOS设备上打开以下链接:https : //daguy.github.io/ios-modal-fix/