網頁佈局裡,「讓一個 div 在畫面正中央」是個經典需求。純 CSS 的做法在舊瀏覽器上常常要靠猜,而 jQuery 可以直接讀取元素尺寸來計算,思路清晰又不挑環境。下面按複雜度遞增,整理四種寫法。
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
原理是先用 top/left 50% 把元素左上角推到畫面中心,再用負的 margin 把自己拉回一半的寬高。前提是元素必須是絕對或固定定位。
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
呼叫方式:
$('#mainDiv').center();
這裡改用 outerHeight() 與 outerWidth(),把邊框與內距計入計算,比單純用 height/width 更準。同時用 top > 0 ? top : 0 做了下限保護,避免元素比視窗還大時被推到負座標。
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
這份寫法把幾個實務上真正會遇到的問題都處理掉了:
inside:不一定每個需求都是對視窗居中,也可能是對某個容器居中。withScrolling:頁面捲動後,若容器本身可捲動,需要把 scrollTop / scrollLeft 加回來,否則位置會跑掉。minX / minY:設定座標下限,避免元素被推到看不見的地方。transition:需要平滑移動時,直接改走 animate 而不是 css。$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
加上 resize 監聽之後,無論用戶怎麼拉動視窗,元素都會重新對齊中心,並帶 300 毫秒的過渡動畫。
整段程式碼寫得相當克制:一個 $.extend 處理預設值,一個 each 支援集合操作,其餘全是清楚的條件判斷。既能直接拿來用,也很適合當作撰寫 jQuery 插件的範本——由簡入繁、層層遞進,卻始終保持可讀。