繁体   English   中英

jQuery的div高度不正确

[英]jQuery doesn't take the correct div height

我的jQuery有问题:我正在使用一个脚本,该脚本允许我通过给它们提供一个类来使元素居中,但是此脚本的高度不正确。

这是我的HTML代码:

    <div class="logoutscreen blackbackground">
        <div class="window centered" style="display: block;">
       [CONTENT HERE]
       </div>
    </div>

这是我的jQuery代码:

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

问题在于,脚本不会采用.centered类(.window)的div的Height和Width,而采用其父级(.logoutscreen)的div的Height和Width。

为什么会这样? :(

$(this)是您在这里遇到的问题。 与其他方法不同,您无法在jQuery的.css()方法中$('.centered')访问this父对象...它将默认为全局window对象。

您要做的是缓存对象并显式引用它:

var $centered = $('.centered');

$centered.css({
    position:'absolute',
    left:'50%',
    top:'50%',
    marginLeft:((-1 * $centered.outerWidth()) / 2),
    marginTop:((-1 * $centered.outerHeight()) / 2)
});

这应该给您您想要的东西。 但是,如果您有多个实例,则需要执行以下操作:

$centered.each(function(){
    var $self = $(this);

    $self.css({
        position:'absolute',
        left:'50%',
        top:'50%',
        marginLeft:((-1 * $self.outerWidth()) / 2),
        marginTop:((-1 * $self.outerHeight()) / 2)
    });
});

这样,每个独特的heightwidth都会得到尊重。

this不是$('.centered')

采用:

$(function () {
    var centered = $('.centered').first();
    centered.css({
        'position': 'absolute',
        'left': '50%',
        'top': '50%',
        'margin-left': -centered.outerWidth() / 2,
        'margin-top': -centered.outerHeight() / 2
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM