jQuery get position of element relative to another element

后端 未结 4 1809
旧时难觅i
旧时难觅i 2020-12-08 18:28

So I have a div like:

And I want to know the position

相关标签:
4条回答
  • 2020-12-08 18:48

    The problem for me was the fact that I was in a div with a scrollbar and that I had to be able to take into account the hidden part down to the root element.

    If I use ".offset()" it gave me wrong values, because it does not take into consideration the hide part of scrollbar as it is relative to the document.

    However, I realized that the ".offsetTop" property relative to its first parent positioned (offsetParent) was always correct. So I made a loop to go recursively to the root element by additionning the values of ".offsetTop":

    I did my own jquery function for that:

    jQuery.fn.getOffsetTopFromRootParent = function () {
        let elem = this[0];
        let offset = 0;
        while (elem.offsetParent != null) {
            offset += elem.offsetTop;
            elem = $(elem.offsetParent)[0];
            if (elem.offsetParent === null) {
                offset += elem.offsetTop;
            }
        }
        return offset;
    };
    

    You can use the same with ".offsetLeft" I suppose...

    If you want to get position of element relative to another element to answer the question:

    let fromElem = $("#fromElemID")[0];
    let offset = 0;
    while (fromElem.id.toUpperCase() != "toElemID".toUpperCase()) {
        offset += fromElem.offsetTop;
        fromElem = $(fromElem.offsetParent)[0];
    }
    return offset;
    

    An element (offsetParent) is said to be positioned if it has a CSS position attribute of relative, absolute, or fixed.

    0 讨论(0)
  • 2020-12-08 18:56

    You're missing the point here....

    Besides that, try:

    myPosY = $('.trigger').offset().left - $('.uiGrid').offset().left;
    myPosX = $('.trigger').offset().top - $('.uiGrid').offset().top;
    
    0 讨论(0)
  • 2020-12-08 18:58

    just do the subtraction your self...

    var relativeY = $("elementA").offset().top - $("elementB").offset().top;

    0 讨论(0)
  • 2020-12-08 19:03

    what you can do here is basically, subtract parent property value from child property value.

    var x = $('child-div').offset().top - $('parent-div').offset().top;
    
    0 讨论(0)
提交回复
热议问题