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">×</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>
效果圖如下:
作者:ZHF
出處:http://zhf.cnblogs.com/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。