我正在使用自举模式并希望将其居中(基于窗口宽度/高度的宽度和高度)。
我试过这个:
(function(global) {
let W = $(global).width(),
H = $(global).height();
// console.log($('.modal .modal-content').width()); // -2
// console.log($('.modal .modal-content').height()); // -2
$('.modal').on('shown.bs.modal', function() {
let $content = $(this).find('.modal-content');
let w = $content.width(),
h = $content.height();
$content.css({
'margin-left': (W / 2) - (w / 2),
'margin-top': (H / 2) - (h / 2)
});
});
}(window));

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
&#13;
有效。但是the problem
(对我来说)是:代码在显示之前不会使模态居中。我想先把它集中在一起。我也试过了show.bs.modal
但是它出了问题。
然后,我试图在加载前获取内容的宽度和高度:
console.log($('.modal .modal-content').width()); // -2
console.log($('.modal .modal-content').height()); // -2
模态已成功附加到body标签上,但我还没有获得宽度和高度。
我可以在哪里编辑?谢谢!