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

前端 未结 13 1723
北恋
北恋 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:54

    warning warning warning warning warning warning

    "Classic case" - URL "/#about-us" and div with an id of "about-us". In this case, the top position set by default anchor click behavior (So the top is 0 for about-us div). You must prevent default (Or you'll go crazy for why it doesn't work -or- any other code you find out there). More details below under "warning".

    1

    Less than 30 seconds solution (Two lines of code "hello world"):

    get your element:

    var element = document.getElementById("hello");
    

    Get getBoundingClientRect ();

    The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport. https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

    var rect = element.getBoundingClientRect();
    

    Return object:

    Dot notation top

    var distance_from_top = rect.top; /* 1007.9971313476562 */
    

    Thats it.

    2

    StackOverflow nightmare 2 - set scroll position to this value

    Again "hello world" (8,000 answers out there - 7,999 not working or to complex).

    https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

      window.scrollTo({
        top: element.getBoundingClientRect().top,
        behavior: 'smooth'
      });
    

    Add offset value to top if you want (For sticky navbars).

    "Hello World" code snippet (Get distance from top viewport + click to scrollTo)

    var element = document.getElementById("hello");
    var rect = element.getBoundingClientRect();
    var distance_from_top = rect.top; /* 50px */
    console.log(distance_from_top);
    
    function scrollTovView(){
      window.scrollTo({
        top: distance_from_top,
        behavior: 'smooth'
      });
    }
    div{
      text-align:center;
      border: 1px solid lightgray;
    }
    
    
    50px height

    warning

    scrollTo "conflict" with main anchor navbars

    This trick is very buggy if, for example, you use this URL (ID to anchor URL)(Top is 0 or "get crazy" hh).

    www.mysite/about#hello
    
      window.scrollTo({
        top: element.getBoundingClientRect().top,
        behavior: 'smooth'
      });
    

    For this code to work you should add:

        if (this.hash !== "") {
          // Prevent default anchor click behavior
          event.preventDefault();
    

    Basic example her: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp

提交回复
热议问题