仅限 IOS/iPhone X/iPhone 7 等
即使是 jquery 模态库也不行! https://jquerymodal.com/ - 打开 iPhone 上的模式,您将能够滚动正文。
我发现很难找到一种解决方案来停止正文滚动,而不会在每次打开模式时让页面跳转到顶部(这与页面滚动一样糟糕的体验)
这似乎是一个大问题,很多人都遇到过这个问题。正如您在这里看到的:
- How to prevent body scrolling on iOS 12 when modal opened?
- 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
都将固定在适当的位置,并调整为与视口(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);
});
});
但是,由于 window
的 scrollTop
值仍然是 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/