下面是一個全面的解決方案,保存原始寬度並使用它計算顯示的事件和文檔大小的寬度和左邊距百分比。最初隱藏對話框以防止閃爍效應。
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="display:none;">
<img src="http://pdf.buildasign.com/upload/images/templateImages/TC17819031-42-260-195-7357-11-SharedDesign.png">
<br>
<p>hello</p>
</div>
</div>
function hCenterModals() {
function toP(n) { return (n * 100).toFixed() + '%'; }
$('.modal').each(function() {
var modalDialog = $(this).find('.modal-dialog'),
modalContent = $(this).find('.modal-content');
// get/save minWidth to data (for resize)
var minWidth = modalDialog.data('minWidth');
if (!minWidth) {
minWidth = modalContent.width();
if (minWidth > 0) {
modalDialog.data('minWidth', minWidth);
console.log('saved ' + minWidth);
} else {
minWidth = 0;
}
}
if (minWidth>0 && modalDialog.is(':visible')) {
var widthFrac = minWidth/$(window).width();
modalDialog.css({
'width': toP(widthFrac),
'margin-left': toP((1 - widthFrac)/2)
});
}
});
}
$('#myModal').on('shown.bs.modal', function (e) {
hCenterModals();
var modalContent = $(this).find('.modal-content');
modalContent.show();
});
$(window).resize(hCenterModals).trigger("resize");
看到jsfiddle
你嘗試添加寬度自動模態內容呢? –
你將無法使用CSS來做到這一點;該模式需要左側和右側邊距的定義寬度才能起作用。 –