在用bootstrap模态框时,特别是小尺寸的模态框时,其显示位置接近屏幕顶端,在网上查找之后,找到了让模态框居中显示的实现。代码如下
function centerModals(){
$('.modal').each(function (i) {
var $clone = $(this).clone().css('display', 'block').appendTo('body');
var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
top = top > 0 ? top : 0;
$clone.remove();
$(this).find('.modal-content').css("margin-top", top);
});
}
$('#question_modal').on('show.bs.modal', centerModals); //question_modal是html中模态框的id
$(window).on('resize', centerModals);