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

  效果圖以下:

  若是你們還有其它的方法或者好的建議,歡迎提出交流分享。

相關文章
相關標籤/搜索