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

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

    Here is some interesting code for you :)

    window.addEventListener('load', function() {
      //get the element
      var elem = document.getElementById('test');
      //get the distance scrolled on body (by default can be changed)
      var distanceScrolled = document.body.scrollTop;
      //create viewport offset object
      var elemRect = elem.getBoundingClientRect();
      //get the offset from the element to the viewport
      var elemViewportOffset = elemRect.top;
      //add them together
      var totalOffset = distanceScrolled + elemViewportOffset;
      //log it, (look at the top of this example snippet)
      document.getElementById('log').innerHTML = totalOffset;
    });
    #test {
      width: 100px;
      height: 100px;
      background: red;
      margin-top: 100vh;
    }
    #log {
      position: fixed;
      top: 0;
      left: 0;
      display: table;
      background: #333;
      color: #fff;
    }
    html,
    body {
      height: 2000px;
      height: 200vh;
    }
    <div id="log"></div>
    <div id="test"></div>

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