jquery inconsistent positioning using offset().top

巧了我就是萌 提交于 2019-12-11 05:56:00

问题


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.



来源:https://stackoverflow.com/questions/14744431/jquery-inconsistent-positioning-using-offset-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!