当页面加载div获取垂直,不水平,直到我调整浏览器大小。
我究竟做错了什么?
$(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 }); });
更新:
我正在更新解决方案,如用户Fred K建议,使用.outerWidth()
和.outerHeight()
有一个更精确的中心。
$(function() { $('.className').css({ 'position' : 'absolute','margin-left' : -$('.className').outerWidth()/2,'margin-top' : -$('.className').outerHeight()/2 }); });
jQuery的文档(.outerWidth()
,.outerHeight()
)中的一些附加注释:
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.
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().
更新2:
一个简单的更新,以显示如何在css()方法中使用这种方法,以防有更多的元素具有相同的类标签不同的大小。
$(function() { $('.className').css({ 'position' : 'absolute','margin-left' : function() {return -$(this).outerWidth()/2},'margin-top' : function() {return -$(this).outerHeight()/2} }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。