在内容加载后垂直重新居中引导模式

Re-center bootstrap modal vertically after content has loaded

本文关键字:新居中 模式 垂直 加载      更新时间:2023-09-26

我已经成功地使用解决方案来居中一个引导模态:

演示:http://codepen.io/dimbslmh/full/mKfCc代码:http://codepen.io/dimbslmh/pen/mKfCc

var contentHeight = $(window).height() - 60;
var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;

但是,它不能很好地处理远程加载的内容。它在内容加载前计算高度。然后,在内容加载之后,位置就偏离了。

我尝试了各种方法将计算延迟一段时间,但这些方法导致模态加载在页面顶部,然后跳到中间。

似乎最好的解决方案是在内容加载后重新计算高度。这样,较小的模态(没有内容)将在中心加载,然后在内容加载后重新居中。

是否有好的方法来做到这一点?

根据文档,有一个名为loaded.bs.modal的方法,其中事件'…当模态使用remote选项加载了内容时触发。

那么在你的代码中,它应该是这样的:

$('#myModal').on('loaded.bs.modal', function () {
  var contentHeight = $(window).height() - 60;
  var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
  var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;
});

这是一个应该可以工作的PEN分支(还没有测试过远程源代码)http://codepen.io/craigmdennis/pen/fChIm

根据注释更新

在计算宽度之前显示模态&高度,然后在得到它们后将其居中。你不能从隐藏对象中获得维度,因为它们在显示之前没有任何维度。你必须添加一个类的模式标记,这样你就可以设置visibility: hidden;z-index: -99;(所以它是不可见的,背后的任何内容,所以不可点击),然后删除类时,loaded.bs.modal事件被触发。

CSS中:

.invisible {
  visibility: hidden;
  position: absolute; /* It will already have a position declaration */
  z-index: -99;
}

然后在JavaScript中:

$('#myModal').on('loaded.bs.modal', function () {
  var contentHeight = $(window).height() - 60;
  var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
  var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;
  $(this).removeClass('invisible');
});