Retrieve the position (X,Y) of an HTML element relative to the browser window

前端 未结 27 3778
闹比i
闹比i 2020-11-21 04:59

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript relative to the browser window.

27条回答
  •  太阳男子
    2020-11-21 05:42

    If page includes - at least- any "DIV", the function given by meouw throws the "Y" value beyond current page limits. In order to find the exact position, you need to handle both offsetParent's and parentNode's.

    Try the code given below (it is checked for FF2):

    
    var getAbsPosition = function(el){
        var el2 = el;
        var curtop = 0;
        var curleft = 0;
        if (document.getElementById || document.all) {
            do  {
                curleft += el.offsetLeft-el.scrollLeft;
                curtop += el.offsetTop-el.scrollTop;
                el = el.offsetParent;
                el2 = el2.parentNode;
                while (el2 != el) {
                    curleft -= el2.scrollLeft;
                    curtop -= el2.scrollTop;
                    el2 = el2.parentNode;
                }
            } while (el.offsetParent);
    
        } else if (document.layers) {
            curtop += el.y;
            curleft += el.x;
        }
        return [curtop, curleft];
    };
    
    

提交回复
热议问题