jquery inconsistent positioning using offset().top

2019-08-01 04:51发布

问题:

I am simply trying to position #elementA relative to #elementB. Half the time it ends up with one top value, half the time it gets another, and I can't figure out why. #elementA begins with this CSS:

#elementA {
    display: block;
    opacity: 0;
    position: absolute;
    clear: both;
    margin-left: -49px;
}

Then, on $(document).ready(), I set the top value and fade it in.

var p = $('#elementB').offset();
$('#elementA').css({
    top: p.top - 2
});
$('#elementA').animate({opacity: 1}, 400);

Why am I getting inconsistent results? Is there a better way to do this?

回答1:

I found the problem. I thought that because I was executing this on $(document).ready() I wouldn't have to worry about assets loading affecting positioning. But it turned out that an image above #elementA was throwing it off when it didn't load in time. Waiting for $('other image').load() fixes it.