如何在模态打开IOS时禁用正文滚动

问题描述 投票:2回答:2

仅限IOS / iPhone X / iPhone 7等

即使是jquery模态库也行不通! https://jquerymodal.com/ - 打开iPhone上的模态,你就可以滚动身体了。

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

这似乎是很多人经历这个问题的一个大问题。正如你在这里看到的:

我没有运气就抓住了互联网,有没有人有解决方案?!

html css twitter-bootstrap-3 bootstrap-modal
2个回答
7
投票

我创建了以下解决方案,适用于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的顶部,这样看起来滚动位置没有改变:

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

但是,当模态关闭时页面仍会跳到顶部,因为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);  
});

没有必要手动删除body上的固定位置,因为这是通过.modal-open类设置的,当模态关闭时Bootstrap会移除。


演示

把它们放在一起,现在你可以防止iOS上的背景滚动,同时打开一个模态而不会丢失你的滚动位置!

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


-2
投票

嗯,我看到SO上已经有很少的主题了。试试吧?

@supports (-webkit-overflow-scrolling: touch) {
  /* CSS specific to iOS devices */ 
}

@supports not (-webkit-overflow-scrolling: touch) {
  /* CSS for other than iOS devices */ 
}

CSS media query target only iOS devices

© www.soinside.com 2019 - 2024. All rights reserved.