Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - 检索HTML元素的位置(X,Y)(Retrieve the position (X,Y) of an HTML element)

我想知道如何获取JavaScript中imgdiv等HTML元素的X和Y位置。

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct approach is to use element.getBoundingClientRect() :

(正确的方法是使用element.getBoundingClientRect() :)

var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);

Internet Explorer has supported this since as long as you are likely to care about and it was finally standardized in CSSOM Views .

(Internet Explorer自从您很可能就一直在支持此功能,并且最终在CSSOM Views中对其进行了标准化。)

All other browsers adopted it a long time ago .

(其他所有浏览器在很久以前就采用了它。)

Some browsers also return height and width properties, though this is non-standard.

(一些浏览器还返回height和width属性,尽管这是非标准的。)

If you're worried about older browser compatibility, check this answer's revisions for an optimised degrading implementation.

(如果您担心与旧版浏览器的兼容性,请查看此答案的修订版以实现优化的降级实现。)

The values returned by element.getBoundingClientRect() are relative to the viewport.

(element.getBoundingClientRect()返回的值是相对于视口的。)

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>');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...