我爲網站設計了一個JQuery插件,目的是幫助使用像素而不是百分比使用絕對位置居中。 頁面開始時,元素垂直居中但不水平(margin-left = 0)。當我在控制檯中使用相同的腳本時,我適用於一個元素,它的工作原理。jquery絕對中心返回margin-left 0
代碼以追加功能:
$(document).ready(function() {
$(element).psfCenter();
});
功能:
(function ($){
// center element
$.fn.psfCenter=function(orientation){
return this.each(function() {
var widthParent=$(this).parent().width()/2;
var heightParent=$(this).parent().height()/2;
var widthElement=$(this).width()/2;
var heightElement=$(this).height()/2;
var left=widthParent-widthElement;
var top=heightParent-heightElement;
console.log(orientation)
switch(orientation){
case"x":
$(this).css({
'position':'absolute',
'margin-left':left,
})
break;
case "y":
$(this).css({
'position':'absolute',
'margin-top':top
})
break;
default:
$(this).css({
'position':'absolute',
'margin-left':left,
'margin-top':top
})
break;
}
});
};
})(jQuery);
有沒有需要使用'與容限*'絕對定位的元素,用'上,左,右或bottom',而是和檢測位置而不是邊距。 –
不工作... left = 0 :( – Espagnet