检索 HTML 元素的位置 (X,Y) [英] Retrieve the position (X,Y) of an HTML element

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

问题描述

我想知道如何在JavaScript中获取imgdiv等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.

推荐答案

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

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

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

Internet Explorer 一直支持这一点,因为只要您可能关心它,它最终在 CSSOM 视图.所有其他浏览器很久以前就采用了它.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆