Bootstrap模态框(modal)垂直居中

  有段日子没有写文章可,或许由于工做忙的缘由,或者没有什么可写的内容等等,其实这些无非都是为本身找的一种借口。正如常常说的一句话:海绵里面的水挤挤仍是有的,时间挤挤也会有的。这说明的问题只能是本身懒惰的缘由,若是天天都在学习,或者水深火热沉浸在项目中,让你可写的内容仍是挺多了,能够记录本身的学习过程,能够记录项目开发过程当中本身负责的内容,……css

  本身目前参与的项目中用到的技术仍是挺多了,好比:Bootstrap框架、Konckout.js、上传插件uploadify、绘图插件jqplot等等,这样一看真的还很多。bootstrap

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

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

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

  由于以前对Bootstrap也不是很熟悉,便开始baidu、google,发现只有不多的解决方案,以下:this

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

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

  这种方法本身试了一下,并不能彻底居中,而且窗口的大小不同的话,每次显示的margin-top值也会改变,遮盖层还会出现滚动条,效果也很差看。spa

  本身也试了改了几种方式也不容乐观,发如今窗口弹出以前是获取不到$(this).height()的值,本想着是用($(window).height()-$(this).height())/2,发现仍是不可行。插件

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

1 that.$element.children().eq(0).css("position", "absolute").css({
2           "margin":"0px",
3           "top": function () {
4               return (that.$element.height() - that.$element.children().eq(0).height()-40) / 2 + "px";
5           },
6           "left": function () {
7               return (that.$element.width() - that.$element.children().eq(0).width()) / 2 + "px";
8           }
9       });

  页面代码以下:

 1 <div>
 2     <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
 3         Launch demo modal
 4     </button>
 5     <!-- Modal -->
 6     <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 7         <div class="modal-dialog">
 8             <div class="modal-content">
 9                 <div class="modal-header">
10                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
11                     <h4 class="modal-title" id="myModalLabel">Modal title</h4>
12                 </div>
13                 <div class="modal-body">
14                     ...
15                 </div>
16                 <div class="modal-footer">
17                     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
18                     <button type="button" class="btn btn-primary">Save changes</button>
19                 </div>
20             </div><!-- /.modal-content -->
21         </div><!-- /.modal-dialog -->
22     </div><!-- /.modal -->
23 </div>
View Code

  效果图以下:

  若是你们还有其它的方法或者好的建议,欢迎提出交流分享。

相关文章
相关标签/搜索