How to get the distance from the top for an element?

前端 未结 13 1659
北恋
北恋 2020-12-07 12:13

I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.

相关标签:
13条回答
  • 2020-12-07 12:32
    var distanceTop = element.getBoundingClientRect().top;
    

    For details vist a link:

    https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

    0 讨论(0)
  • 2020-12-07 12:32

    This function returns distance from top of the page, even if your window is scrolled. It can be used in event listeners.

    const getElementYOffset = (element) => {
      const scrollOnWindow =
        window.pageYOffset !== undefined
          ? window.pageYOffset
          : (document.documentElement || document.body.parentNode || document.body)
              .scrollTop;
      const rect = element.getBoundingClientRect();
      let distanceFromTopOfPage = rect.top;
      if (scrollOnWindow !== 0) {
        distanceFromTopOfPage = rect.top + scrollOnWindow;
      }
    
      return distanceFromTopOfPage;
    };
    
    0 讨论(0)
  • 2020-12-07 12:37

    scroll to element's top position;

    var rect = element.getBoundingClientRect();
    var offsetTop = window.pageYOffset + rect.top - rect.height;
    
    0 讨论(0)
  • 2020-12-07 12:40
    var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top
    

    In my experience document.body.scrollTop doesn't always return the current scroll position (for example if the scrolling actually happens on a different element).

    0 讨论(0)
  • 2020-12-07 12:40

    Although it is quite an old discussion, but this works pretty well on chrome / firefox / safari browsers:

    window.addEventListener('scroll', function() {
       var someDiv = document.getElementById('someDiv');
       var distanceToTop = someDiv.getBoundingClientRect().top;
    });
    

    Check it out on JSFiddle

    0 讨论(0)
  • 2020-12-07 12:41

    Using jQuery's offset() method:

    $(element).offset().top
    

    Example: http://jsfiddle.net/yZGSt/3/

    0 讨论(0)
提交回复
热议问题