jQuery get the location of an element relative to window

后端 未结 7 1575
小鲜肉
小鲜肉 2020-11-28 01:20

Given an HTML DOM ID, how to get an element\'s position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent sinc

7条回答
  •  伪装坚强ぢ
    2020-11-28 01:48

    function getWindowRelativeOffset(parentWindow, elem) {
            var offset = {
                left : 0,
                top : 0
            };
            // relative to the target field's document
            offset.left = elem.getBoundingClientRect().left;
            offset.top = elem.getBoundingClientRect().top;
            // now we will calculate according to the current document, this current
            // document might be same as the document of target field or it may be
            // parent of the document of the target field
            var childWindow = elem.document.frames.window;
            while (childWindow != parentWindow) {
                offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
                offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
                childWindow = childWindow.parent;
            }
            return offset;
        };
    

    you can call it like this

    getWindowRelativeOffset(top, inputElement);
    

    I focus for IE only as per my requirement but similar can be done for other browsers

提交回复
热议问题