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

前端 未结 27 4588
闹比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:35

    I did it like this so it was cross-compatible with old browsers.

    // For really old browser's or incompatible ones
        function getOffsetSum(elem) {
            var top = 0,
                left = 0,
                bottom = 0,
                right = 0
    
             var width = elem.offsetWidth;
             var height = elem.offsetHeight;
    
            while (elem) {
                top += elem.offsetTop;
                left += elem.offsetLeft;
                elem = elem.offsetParent;
            }
    
             right = left + width;
             bottom = top + height;
    
            return {
                top: top,
                left: left,
                bottom: bottom,
                right: right,
            }
        }
    
        function getOffsetRect(elem) {
            var box = elem.getBoundingClientRect();
    
            var body = document.body;
            var docElem = document.documentElement;
    
            var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
            var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
    
            var clientTop = docElem.clientTop;
            var clientLeft = docElem.clientLeft;
    
    
            var top = box.top + scrollTop - clientTop;
            var left = box.left + scrollLeft - clientLeft;
            var bottom = top + (box.bottom - box.top);
            var right = left + (box.right - box.left);
    
            return {
                top: Math.round(top),
                left: Math.round(left),
                bottom: Math.round(bottom),
                right: Math.round(right),
            }
        }
    
        function getOffset(elem) {
            if (elem) {
                if (elem.getBoundingClientRect) {
                    return getOffsetRect(elem);
                } else { // old browser
                    return getOffsetSum(elem);
                }
            } else
                return null;
        }
    

    More about coordinates in JavaScript here: http://javascript.info/tutorial/coordinates

提交回复
热议问题