Bootstrap模态框(modal)垂直居中的实例代码

2019-12-04,,

Bootstrap官网下载:http://v3.bootcss.com/

  今天就在使用Bootstrap框架中遇到的一个问题分享一下,在产品开发的过程中使用了大量的弹出窗口(modal)。

  刚开始学习使用的过程中就发现此窗口不能垂直居中,总是偏上,并且不能拖动,看了一下使用说明也没有提供过多的属性设置和方法,就这样使用默认的方式一直用着。最近,客户却提出了一个要求:能不能让弹出窗口居中,因为一些小的窗口偏上总感觉整体页面失衡,大一点的还过得去。

  因为之前对Bootstrap也不是很熟悉,便开始baidu、google,发现只有很少的解决方案,如下:

$("#myModal").modal().css({
"margin-top": function () {
return - ($(this).height() / 2);
}
});

  参考地址:http://www.g2w.me/2012/06/bootstrap-modal-shown-in-the-center/  

  这种方法自己试了一下,并不能完全居中,并且窗口的大小不一样的话,每次显示的margin-top值也会改变,遮盖层还会出现滚动条,效果也不好看。

  自己也试了改了几种方式也不容乐观,发现在窗口弹出之前是获取不到$(this).height()的值,本想着是用($(window).height()-$(this).height())/2,发现还是不可行。

  最终只能研究一下源码了,发现可以在bootstrap.js文件900行后面添加如下代码,便可以实现垂直居中。

that.$element.children().eq(0).css("position", "absolute").css({
"margin":"0px",
"top": function () {
return (that.$element.height() - that.$element.children().eq(0).height()-40) / 2 + "px";
},
"left": function () {
return (that.$element.width() - that.$element.children().eq(0).width()) / 2 + "px";
}
});

  页面代码如下:

<div>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</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><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>

 效果图如下:

以上所述是小编给大家介绍的Bootstrap模态框(modal)垂直居中的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对北冥有鱼网站的支持!

您可能感兴趣的文章:

  • 页面遮罩层,并且阻止页面body滚动。bootstrap模态框原理
  • Bootstrap每天必学之模态框(Modal)插件
  • 浅析BootStrap中Modal(模态框)使用心得
  • Bootstrap 模态框(Modal)带参数传值实例
  • bootstrap模态框消失问题的解决方法
  • 在iframe中使bootstrap的模态框在父页面弹出问题
  • bootstrap 模态框(modal)实现水平垂直居中显示
  • BootStrap 模态框实现刷新网页并关闭功能
  • Bootstrap模态框禁用空白处点击关闭
  • Bootstrap实现模态框效果

《Bootstrap模态框(modal)垂直居中的实例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。