javascript offset() jquery 函数的跨浏览器问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4334664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross browser issue with offset() jquery function
提问by amateur
I am having a cross browser issue with the offset()function in jQuery. For example, I am looking for the offset of an anchor tag
我offset()在 jQuery 中的函数存在跨浏览器问题。例如,我正在寻找锚标记的偏移量
eg. $('#anchorid').offset().top
例如。 $('#anchorid').offset().top
- In Firefox 3.6 = 205
- In IE8 = 204
- In IE7 = 553
- 在 Firefox 3.6 = 205
- 在 IE8 = 204
- 在 IE7 = 553
As you can see the difference in each returned value. I am not too concerned with the difference between FF & IE8 but I am with IE7 and the others.
如您所见,每个返回值的差异。我不太关心 FF 和 IE8 之间的区别,但我很关心 IE7 和其他的。
Is there another function I could use that would be the same or similar cross browsers or a possible fix for this?
是否有另一个我可以使用的功能是相同或相似的跨浏览器或可能的解决方案?
回答by Coin_op
The chances are there is something wrong (non-crossbrowser) with your markup. But as alternative you could try using native javascript instead.
您的标记可能有问题(非跨浏览器)。但作为替代,您可以尝试使用本机 javascript。
document.getElementById('anchorid').offsetTop
Of if you wanted to get the offset on the whole page you could use a function like:
如果你想在整个页面上获得偏移量,你可以使用如下函数:
function findTotalOffset(obj) {
var ol = ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
}while (obj = obj.offsetParent);
}
return {left : ol, top : ot};
}
回答by Leonardo Jauregui
I get this problem in IE8 when my script is loaded on a page where the element that we want to get the offset().topof does not exist.
当我的脚本加载到我们想要获取的元素offset().top不存在的页面上时,我在 IE8 中遇到了这个问题。
I solved it like this:
我是这样解决的:
if ($('#element').length){
$('#element').offset().top // ...
}
Never execute offset().topif the element does not exist.
offset().top如果元素不存在,则永远不要执行。

