Cross browser issue with offset() jquery function

后端 未结 2 855
时光说笑
时光说笑 2020-12-18 01:29

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. $(\'#anchori

相关标签:
2条回答
  • 2020-12-18 01:51

    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};
    }
    
    0 讨论(0)
  • 2020-12-18 01:56

    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 讨论(0)
提交回复
热议问题