本文介绍了jquery使用offset()进行不一致的定位.top的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图将#elementA放在相对于#elementB的位置。一半的时间它最终得到一个最高值,一半时间它得到另一个,我无法弄清楚为什么。 #elementA以此CSS开头:

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;
}

然后,在$(文件).ready()上,我设置了顶部价值并淡入。

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?

推荐答案

我发现了问题。我认为,因为我在$(document).ready()上执行此操作,我不必担心资产加载会影响定位。但事实证明,#elementA上方的图像在未及时加载时将其丢弃。等待$('其他图像').load()修复它。

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.

这篇关于jquery使用offset()进行不一致的定位.top的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 14:47