当页面加载div获取垂直,不水平,直到我调整浏览器大小。@H_403_3@
我究竟做错了什么?@H_403_3@
$(document).ready(function (){ $(window).resize(function (){ $('.className').css({ position:'absolute',left: ($(window).width() - $('.className').outerWidth())/2,top: ($(window).height() - $('.className').outerHeight())/2 }); }); $(window).resize(); });
解决方法
$(function() { $('.className').css({ 'position' : 'absolute','left' : '50%','top' : '50%','margin-left' : -$('.className').width()/2,'margin-top' : -$('.className').height()/2 }); });
更新:@H_403_3@
我正在更新解决方案,如用户Fred K建议,使用.outerWidth()
和.outerHeight()
有一个更精确的中心。@H_403_3@
$(function() { $('.className').css({ 'position' : 'absolute','margin-left' : -$('.className').outerWidth()/2,'margin-top' : -$('.className').outerHeight()/2 }); });
jQuery的文档(.outerWidth()
,.outerHeight()
)中的一些附加注释:@H_403_3@
The number returned by dimensions-related APIs,including .outerWidth(),may be fractional in some cases. Code should not assume it is an integer. Also,dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.@H_403_3@
The value reported by .outerWidth() is not guaranteed to be accurate when the element’s parent is hidden. To get an accurate value,you should show the parent first,before using .outerWidth().@H_403_3@
更新2:@H_403_3@
一个简单的更新,以显示如何在css()方法中使用这种方法,以防有更多的元素具有相同的类标签不同的大小。@H_403_3@
$(function() { $('.className').css({ 'position' : 'absolute','margin-left' : function() {return -$(this).outerWidth()/2},'margin-top' : function() {return -$(this).outerHeight()/2} }); });