最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cross browser issue with offset() jquery function - Stack Overflow

programmeradmin4浏览0评论

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

eg. $('#anchorid').offset().top

  • In Firefox 3.6 = 205
  • In IE8 = 204
  • In 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.

Is there another function I could use that would be the same or similar cross browsers or a possible fix for this?

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

eg. $('#anchorid').offset().top

  • In Firefox 3.6 = 205
  • In IE8 = 204
  • In 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.

Is there another function I could use that would be the same or similar cross browsers or a possible fix for this?

Share Improve this question edited Sep 27, 2013 at 18:47 allicarn 2,9192 gold badges29 silver badges47 bronze badges asked Dec 2, 2010 at 11:52 amateuramateur 44.6k71 gold badges196 silver badges324 bronze badges 1
  • 3 Do you have an example page? That is way off. – Nick Craver Commented Dec 2, 2010 at 12:01
Add a ment  | 

2 Answers 2

Reset to default 10

The chances are there is something wrong (non-crossbrowser) with your markup. But as alternative you could try using native javascript instead.

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

I get this problem in IE8 when my script is loaded on a page where the element that we want to get the offset().top of does not exist.

I solved it like this:

if ($('#element').length){
    $('#element').offset().top // ...
}

Never execute offset().top if the element does not exist.

发布评论

评论列表(0)

  1. 暂无评论