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