获取元素相对于父容器的位置/偏移量

Get position/offset of element relative to a parent container?

本文关键字:位置 偏移量 元素 相对于 获取      更新时间:2024-02-10

如何使用纯JS检索容器相对于父级的偏移量?

element.offsetLeftelement.offsetTop给出元素相对于其offsetParent(位置为relativeabsolute的最近父元素)的位置

在纯js中只使用offsetLeftoffsetTop属性
小提琴示例:http://jsfiddle.net/WKZ8P/

var elm = document.querySelector('span');
console.log(elm.offsetLeft, elm.offsetTop);
p   { position:relative; left:10px; top:85px; border:1px solid blue; }
span{ position:relative; left:30px; top:35px; border:1px solid red; }
<p>
    <span>paragraph</span>
</p>

我在Internet Explorer中就是这样做的。

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;
};

===================你可以这样称呼它

getWindowRelativeOffset(top, inputElement);

我只专注于IE,但其他浏览器也可以做类似的事情。

将事件的偏移量添加到父元素偏移量,以获得事件的绝对偏移位置。

一个例子:

HTMLElement.addEventListener('mousedown',function(e){
    var offsetX = e.offsetX;
    var offsetY = e.offsetY;
    if( e.target != this ){ // 'this' is our HTMLElement
        offsetX = e.target.offsetLeft + e.offsetX;
        offsetY = e.target.offsetTop + e.offsetY;
    }
}

当事件目标不是事件注册到的元素时,它会将父对象的偏移量添加到当前事件偏移量中,以计算"绝对"偏移量值。

根据Mozilla Web API:"HTMLElement.offsetLeft只读属性返回当前元素左上角在HTMLElement.ooffsetParent节点内向左偏移的像素数。"

这种情况主要发生在您在包含多个子项的父项上注册事件时,例如:具有内部图标或文本跨度的按钮,具有内部跨度的li元素。等等。

我得到了另一个解决方案。从子属性值减去父属性值

$('child-div').offset().top - $('parent-div').offset().top;

示例

因此,如果我们有一个id为"的子元素;子元素";我们想得到它相对于父元素的左/顶部位置,比如一个div,它有一个类";项目父项";,我们会使用这个代码。

var position = $("#child-element").offsetRelative("div.item-parent");
alert('left: '+position.left+', top: '+position.top);

插件最后,对于实际的插件(有一些注释解释了发生了什么):

// offsetRelative (or, if you prefer, positionRelative)
(function($){
    $.fn.offsetRelative = function(top){
        var $this = $(this);
        var $parent = $this.offsetParent();
        var offset = $this.position();
        if(!top) return offset; // Didn't pass a 'top' element 
        else if($parent.get(0).tagName == "BODY") return offset; // Reached top of document
        else if($(top,$parent).length) return offset; // Parent element contains the 'top' element we want the offset to be relative to 
        else if($parent[0] == $(top)[0]) return offset; // Reached the 'top' element we want the offset to be relative to 
        else { // Get parent's relative offset
            var parent_offset = $parent.offsetRelative(top);
            offset.top += parent_offset.top;
            offset.left += parent_offset.left;
            return offset;
        }
    };
    $.fn.positionRelative = function(top){
        return $(this).offsetRelative(top);
    };
}(jQuery));

注意:您可以在mouseClick或mouseover Event 上使用

$(this).offsetRelative("div.item-parent");

使用纯JS当然很容易,只需这样做,也适用于固定和动画HTML 5面板,我制作并尝试了这段代码,它适用于任何浏览器(包括IE 8):

<script type="text/javascript">
    function fGetCSSProperty(s, e) {
        try { return s.currentStyle ? s.currentStyle[e] : window.getComputedStyle(s)[e]; }
        catch (x) { return null; } 
    }
    function fGetOffSetParent(s) {
        var a = s.offsetParent || document.body;
        while (a && a.tagName && a != document.body && fGetCSSProperty(a, 'position') == 'static')
            a = a.offsetParent;
        return a;
    }
    function GetPosition(s) {
        var b = fGetOffSetParent(s);
        return { Left: (b.offsetLeft + s.offsetLeft), Top: (b.offsetTop + s.offsetTop) };
    }    
</script>