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

前端 未结 13 1713
北恋
北恋 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

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

提交回复
热议问题