html - 如何在模态打开时禁用正文滚动仅限 IOS

标签 html css twitter-bootstrap-3 bootstrap-modal

仅限 IOS/iPhone X/iPhone 7 等

即使是 jquery 模态库也不行! https://jquerymodal.com/ - 打开 iPhone 上的模式,您将能够滚动正文。

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

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

我已经在互联网上搜寻但没有运气,有人有解决方案吗?!

最佳答案

我创建了以下适用于 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 都将固定在适当的位置,并调整为与视口(viewport)本身相同的尺寸。这完全阻止了滚动,因为没有任何地方可以滚动到任何地方!

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

第 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);
    });
});

但是,由于 windowscrollTop 值仍然是 0,所以当 modal 关闭时,页面仍然会跳到顶部。

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

现在我们只需要 Hook 到模式关闭时触发的事件并将所有内容恢复原样:

  • 去掉body上的固定定位和负top值
  • 将窗口的滚动位置设置回原来的位置
$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/

关于html - 如何在模态打开时禁用正文滚动仅限 IOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54786905/

相关文章:

html - 将两个 div 与所有设备的图像和文本对齐

html - 无法设计 HTML/CSS block ,无法使用 bootstrap 来对齐图像

html - 设置 Font awesome 并输入相同高度的 HTML, CSS

html - 如何使用 CSS 制作 CSS 下拉菜单?

javascript - 用于移动设备的 HTML5 拖放

html - CSS 网格 - 图像上的文本框

javascript - 3D卡片翻转: CSS scaling while maintaing image clarity

javascript - 如何制作不阻止链接的 CSS 元素

html - 右外边距为负的 float 元素

javascript - 滚动时更改 bootstrap 3 导航栏的颜色