Javascript 查找元素相对于文档的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5598743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding element's position relative to the document
提问by einstein
What's the easiest way to determine an elements position relative to the document/body/browser window?
确定元素相对于文档/正文/浏览器窗口的位置的最简单方法是什么?
Right now I'm using .offsetLeft/offsetTop
, but this method only gives you the position relative to the parent element, so you need to determine how many parents to the body element, to know the position relaltive to the body/browser window/document position.
现在我正在使用.offsetLeft/offsetTop
,但这种方法只为您提供相对于父元素的位置,因此您需要确定 body 元素有多少个父元素,以了解相对于 body/浏览器窗口/文档位置的位置。
This method is also to cumbersome.
这种方法也很麻烦。
采纳答案by KeatsKelleher
You can traverse the offsetParent
up to the top level of the DOM.
您可以遍历offsetParent
到 DOM 的顶层。
function getOffsetLeft( elem )
{
var offsetLeft = 0;
do {
if ( !isNaN( elem.offsetLeft ) )
{
offsetLeft += elem.offsetLeft;
}
} while( elem = elem.offsetParent );
return offsetLeft;
}
回答by basil
You can get topand leftwithout traversing DOM like this:
您可以像这样在不遍历 DOM 的情况下获得top和left:
function getCoords(elem) { // crossbrowser version
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
回答by dy_
You can use element.getBoundingClientRect()
to retrieve element position relative to the viewport.
您可以使用element.getBoundingClientRect()
检索相对于视口的元素位置。
Then use document.documentElement.scrollTop
to calculate the viewport offset.
然后用于document.documentElement.scrollTop
计算视口偏移。
The sum of the two will give the element position relative to the document:
两者之和将给出元素相对于文档的位置:
element.getBoundingClientRect().top + document.documentElement.scrollTop
回答by Mathieu M-Gosselin
document-offset
(3rd-party script) is interesting and it seems to leverage approaches from the other answers here.
document-offset
(3rd-party script)很有趣,它似乎利用了这里其他答案的方法。
Example:
例子:
var offset = require('document-offset')
var target = document.getElementById('target')
console.log(offset(target))
// => {top: 69, left: 108}
回答by HANiS
I suggest using
我建议使用
element.getBoundingClientRect()
as proposed hereinstead of manual offset calculation through offsetLeft, offsetTopand offsetParent. as proposed hereUnder some circumstances* the manual traversal produces invalid results. See this Plunker: http://plnkr.co/pC8Kgj
如此处所建议的,而不是通过offsetLeft、offsetTop和offsetParent手动计算偏移量。如提出这里在某些情况下*手动遍历产生无效的结果。看到这个Plunker:http://plnkr.co/pC8Kgj
*When element is inside of a scrollable parent with static (=default) positioning.
*当元素位于具有静态(=默认)定位的可滚动父级内时。
回答by Robin Stewart
I've found the following method to be the most reliable when dealing with edge cases that trip up offsetTop/offsetLeft.
我发现以下方法在处理触发 offsetTop/offsetLeft 的边缘情况时是最可靠的。
function getPosition(element) {
var clientRect = element.getBoundingClientRect();
return {left: clientRect.left + document.body.scrollLeft,
top: clientRect.top + document.body.scrollTop};
}
回答by Raphael Rafatpanah
For those that want to get the x and y coordinates of various positions of an element, relative to the document.
对于那些想要获取元素不同位置的 x 和 y 坐标的人,相对于文档。
const getCoords = (element, position) => {
const { top, left, width, height } = element.getBoundingClientRect();
let point;
switch (position) {
case "top left":
point = {
x: left + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top right":
point = {
x: left + width + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "center left":
point = {
x: left + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center right":
point = {
x: left + width + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "bottom left":
point = {
x: left + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom right":
point = {
x: left + width + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
}
return point;
};
Usage
用法
getCoords(document.querySelector('selector'), 'center')
getCoords(document.querySelector('selector'), 'bottom right')
getCoords(document.querySelector('selector'), 'top center')
getCoords(document.querySelector('selector'), 'center')
getCoords(document.querySelector('selector'), 'bottom right')
getCoords(document.querySelector('selector'), 'top center')
回答by Adam
If you don't mind using jQuery, then you can use offset()
function. Refer to documentationif you want to read up more about this function.
如果您不介意使用 jQuery,那么您可以使用offset()
函数。如果您想阅读有关此功能的更多信息,请参阅文档。
回答by Jake Kalstad
http://www.quirksmode.org/js/findpos.htmlExplains the best way to do it, all in all, you are on the right track you have to find the offsets and traverse up the tree of parents.
http://www.quirksmode.org/js/findpos.html解释了最好的方法,总而言之,你走在正确的轨道上,你必须找到偏移量并遍历父树。