简体   繁体   中英

jQuery doesn't take the correct div height

i've a problem with my jQuery: i'm using a script that allows me to center elements by giving them a class, but this script doesn't take the correct height.

This is my HTML code:

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

And this my jQuery code:

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

The problem is that the script doesn't take Height and Width of the div with .centered class (.window), but of his parent (.logoutscreen).

Why this happens? :(

The use of $(this) is your problem here. Unlike other methods, you cannot access the this parent object as $('.centered') in jQuery's .css() method ... it will default to the global window object.

What you want to do is cache your object and reference it explicitly:

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

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

This should give you what you're looking for. If you have multiple instances, however, you'll need to do something like this:

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

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

That way each unique height and width is respected.

this is not $('.centered') .

Use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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