Bootstrap模態框(modal)垂直居中

  有段日子沒有寫文章可,或許因爲工作忙的原因,或者沒有什麼可寫的內容等等,其實這些無非都是爲自己找的一種藉口。正如經常說的一句話:海綿裏面的水擠擠還是有的,時間擠擠也會有的。這說明的問題只能是自己懶惰的原因,如果每天都在學習,或者水深火熱沉浸在項目中,讓你可寫的內容還是挺多了,可以記錄自己的學習過程,可以記錄項目開發過程中自己負責的內容,……

  自己目前參與的項目中用到的技術還是挺多了,比如:Bootstrap框架、Konckout.js、上傳插件uploadify、繪圖插件jqplot等等,這樣一看真的還不少。

  Bootstrap官網下載:http://v3.bootcss.com/

  今天就在使用Bootstrap框架中遇到的一個問題分享一下,在產品開發的過程中使用了大量的彈出窗口(modal)。

  剛開始學習使用的過程中就發現此窗口不能垂直居中,總是偏上,並且不能拖動,看了一下使用說明也沒有提供過多的屬性設置和方法,就這樣使用默認的方式一直用着。最近,客戶卻提出了一個要求:能不能讓彈出窗口居中,因爲一些小的窗口偏上總感覺整體頁面失衡,大一點的還過得去。

  因爲之前對Bootstrap也不是很熟悉,便開始baidu、google,發現只有很少的解決方案,如下:

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/  

  這種方法自己試了一下,並不能完全居中,並且窗口的大小不一樣的話,每次顯示的margin-top值也會改變,遮蓋層還會出現滾動條,效果也不好看。

  自己也試了改了幾種方式也不容樂觀,發現在窗口彈出之前是獲取不到$(this).height()的值,本想着是用($(window).height()-$(this).height())/2,發現還是不可行。

  最終只能研究一下源碼了,發現可以在bootstrap.js文件900行後面添加如下代碼,便可以實現垂直居中。

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

  效果圖如下:

  如果大家還有其它的方法或者好的建議,歡迎提出交流分享。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章