检索HTML元素相对于浏览器窗口的位置(X,Y) [英] Retrieve the position (X,Y) of an HTML element relative to the browser window
问题描述
我想知道如何获取HTML元素(例如img
和div
)在HTML中相对于浏览器窗口的X和Y位置.
I want to know how to get the X and Y position of HTML elements such as img
and div
in JavaScript relative to the browser window.
推荐答案
The correct approach is to use element.getBoundingClientRect()
:
var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
Internet Explorer自从您很可能就一直在支持此功能,并且最终在很久以前.
Internet Explorer has supported this since as long as you are likely to care about and it was finally standardized in CSSOM Views. All other browsers adopted it a long time ago.
某些浏览器还返回height和width属性,尽管这是非标准的.如果您担心与旧版浏览器的兼容性,请查看此答案的修订版,以实现优化的降级实现.
Some browsers also return height and width properties, though this is non-standard. If you're worried about older browser compatibility, check this answer's revisions for an optimised degrading implementation.
element.getBoundingClientRect()
返回的值是相对于视口的.如果您需要相对于另一个元素的矩形,只需从另一个矩形中减去一个矩形:
The values returned by element.getBoundingClientRect()
are relative to the viewport. If you need it relative to another element, simply subtract one rectangle from the other:
var bodyRect = document.body.getBoundingClientRect(),
elemRect = element.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
alert('Element is ' + offset + ' vertical pixels from <body>');
这篇关于检索HTML元素相对于浏览器窗口的位置(X,Y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!