检索HTML元素的位置

检索HTML元素的位置

本文介绍了检索HTML元素的位置(X,Y)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何获取HTML元素的X和Y位置,例如 img div JavaScript。

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript.

推荐答案

正确的方法是使用:

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.

某些浏览器还会返回高度和宽度属性,但这是非标准的。

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!