如何在模式打开时禁用正文滚动(仅限 IOS)

2024-03-15

仅限 IOS / iPhone X / iPhone 7 等

甚至 jquery 模态库也不起作用!https://jquerymodal.com/ https://jquerymodal.com/- 在 iPhone 上打开模态框,您将能够滚动正文。

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

这似乎是一个大问题,很多人都遇到过这个问题。正如你在这里看到的:

  • 当模式打开时,如何防止 iOS 12 上的主体滚动? https://stackoverflow.com/questions/53278783/how-to-prevent-body-scrolling-on-ios-12-when-modal-opened
  • https://stackoverflow.com/questions/49760984/stopping-body-scroll-on-modal-open-bootstrap-4 https://stackoverflow.com/questions/49760984/stopping-body-scroll-on-modal-open-bootstrap-4

我在网上查了好久都没有成功,请问有解决办法吗?


我创建了以下解决方案,适用于 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;
    }
}

现在,每当打开模式时,body将被固定到位并调整为与视口本身相同的尺寸。这完全阻止了滚动,因为没有地方也没有东西可以滚动!

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

第 2 步:模拟模态框打开时的上一个滚动距离

Bootstrap 公开打开或关闭模式时触发的事件。我们可以使用它们通过拉动顶部来解决“跳到顶部”问题body up当模式打开时,看起来滚动位置没有改变:

$(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);
    });
});

但是,当模态框关闭时,页面仍然会跳转到顶部,因为scrollTop的值window还是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);  
});

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


Demo

将它们放在一起,现在您可以在模式打开时防止 iOS 上的后台滚动,而不会丢失滚动位置!

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在模式打开时禁用正文滚动(仅限 IOS) 的相关文章