gpt4 book ai didi

jquery - 使用 jQuery 将 div 垂直和水平居中

转载 作者:行者123 更新时间:2023-12-03 21:29:58 25 4
gpt4 key购买 nike

我正在使用此脚本将我的 div 水平和垂直居中。

当页面加载时,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',
'left' : '50%',
'top' : '50%',
'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() 方法中使用 this,以防有更多元素具有相同的 class不同尺寸的标签。

$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : function() {return -$(this).outerWidth()/2},
'margin-top' : function() {return -$(this).outerHeight()/2}
});
});

关于jquery - 使用 jQuery 将 div 垂直和水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13903556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com