将纯Javascript复制到$ .offset和$ .position

See*_*uth 4 javascript reactjs

我正在为Reactjs构建覆盖机制,并在Reactjs中使用Jquery就像用锤子砸拇指一样。你不做。

所以我在jQuery中有这两个功能非常有用

window.jQuery(DOMNode).offset();
window.jQuery(elem).position();
Run Code Online (Sandbox Code Playgroud)

我到处都在寻找javascript等效项。我什至查看了它们的实现细节,但是可惜我不想正确复制它,因为那和使用它们自己的功能是一样的。

有人知道有什么函数会让我获得这些函数的相同或相似的返回值吗?

Che*_*ery 5

您可以使用类似这样的东西(它不会检查元素的存在)

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);
Run Code Online (Sandbox Code Playgroud)
#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%;
}
Run Code Online (Sandbox Code Playgroud)
<div id='parent'>
    <div id='element'>
        Test
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

相对于窗口的偏移结果不同于75和25,这是因为浏览器的默认边距<body>可以通过以下方式设置为0:body {margin: 0px;}