Get position of element by JavaScript

后端 未结 4 879
南笙
南笙 2020-12-13 21:43

I\'ve seen dozens of scripts that can catch the x and y position of an element/object within the page. But I am always having trouble with catching the x and y when the webp

4条回答
  •  盖世英雄少女心
    2020-12-13 22:19

    Getting the exact position is simply a matter of adding the offsetLefts and offsetTops recursively to the offsetParents:

    function getPos(ele){
        var x=0;
        var y=0;
        while(true){
            x += ele.offsetLeft;
            y += ele.offsetTop;
            if(ele.offsetParent === null){
                break;
            }
            ele = ele.offsetParent;
        }
        return [x, y];
    }
    

    Btw, this solution would probably run twice faster than the other solution above since we only loop once.

提交回复
热议问题