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)垂直居中的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答