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

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

    offsetTop only looks at the element's parent. Just loop through parent nodes until you run out of parents and add up their offsets.

    function getPosition(element) {
        var xPosition = 0;
        var yPosition = 0;
    
        while(element) {
            xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
            yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
            element = element.offsetParent;
        }
    
        return { x: xPosition, y: yPosition };
    }
    

提交回复
热议问题