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

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

    offsetTop doesn’t get the distance to the top of the page, but rather to the top of the closest parent element that has a specified position.

    You can use a simple technique that adds up the offsetTop of all the parent element of the element you are interested in to get the distance.

    // Our element
    var elem = document.querySelector('#some-element');
    
    // Set our distance placeholder
    var distance = 0;
    
    // Loop up the dom
    do {
        // Increase our distance counter
        distance += elem.offsetTop;
    
        // Set the element to it's parent
        elem = elem.offsetParent;
    
    } while (elem);
    distance = distance < 0 ? 0 : distance;
    

    Original code from https://gomakethings.com/how-to-get-an-elements-distance-from-the-top-of-the-page-with-vanilla-javascript/

提交回复
热议问题