Cross browser issue with offset() jquery function

浪尽此生 提交于 2019-11-29 06:59:48

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};
}
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().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.

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