Normal Javascript replication for $ .offset and $ .position

I am creating a mechanism for Reactjs, and using jQuery in Reactjs is like breaking a thumb with a hammer. You do not do this.

So, I have two functions in jquery that are very useful

window.jQuery(DOMNode).offset();
window.jQuery(elem).position();

I looked at everything where for javascript equivalents. I even looked at their implementation details, but, alas, I do not want our right-hand copy, because it's good that it will be the same as just using the functions themselves.

Does anyone know of any functions that get me the same or similar return values ​​of these functions?

+4
source share
3 answers

- ( )

function getOffset(element, target) {
    var element = document.getElementById(element),
        target  = target ? document.getElementById(target) : window;
    var offset = {top: element.offsetTop, left: element.offsetLeft},
        parent = element.offsetParent;
    while (parent != null && parent != target) {
       offset.left += parent.offsetLeft;
       offset.top  += parent.offsetTop;
       parent = parent.offsetParent;
    }
    return offset;
}

var tmp = getOffset('element', 'parent');
alert('Offset to parent top = ' + tmp.top + ' and left = ' + tmp.left);
var tmp = getOffset('element');
alert('Offset to window top = ' + tmp.top + ' and left = ' + tmp.left);
#parent {
    position: relative;
    top: 50px;
    left: 50px;
    border: 1px solid red;
    width: 50%;
}

#element {
    position: relative;
    top: 25px;
    left: -25px;
    border: 1px solid blue;
    width: 50%;
}
<div id='parent'>
    <div id='element'>
        Test
    </div>
</div>
Hide result

75 25, <body>, ​​ 0 body {margin: 0px;}

+4

, jquery:

function find_PosX(obj){
    var curleft=0;
    if(obj.offsetParent)
        while(1){
            curleft+=obj.offsetLeft;
            if(!obj.offsetParent)
                break;
                obj=obj.offsetParent;
        }
    else if(obj.x)curleft+=obj.x;
    return curleft;
}

function find_PosY(obj){
    var curtop=0;
    if(obj.offsetParent)
        while(1){
            curtop+=obj.offsetTop;
            if(!obj.offsetParent)
                break;
                obj=obj.offsetParent;
        }
    else if(obj.y)curtop+=obj.y;
    return curtop;
}
0

I use

elOffsetTop = el.offsetTop - el.scrollTop + el.parentNode.offsetTop - el.parentNode.scrollTop;
elOffsetLeft = el.offsetLeft - el.scrollLeft + el.parentNode.offsetLeft - el.parentNode.scrollLeft;
Run codeHide result

I just went into it and it was better for me.

0
source

All Articles