检索HTML元素相对于浏览器窗口的位置(X,Y) [英] Retrieve the position (X,Y) of an HTML element relative to the browser window

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

问题描述

我想知道如何获取HTML元素(例如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 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屋!

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