javascript 有没有办法获得 DOM 元素的边界框(以像素为单位)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9287594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:11:28  来源:igfitidea点击:

Is there a way to get the bounding box (in pixels) of a DOM element?

javascripthtmlcss

提问by Aletheios

Is there a way to get the bounding box coordinates of a DOM element with Javascript?

有没有办法用Javascript获取DOM元素的边界框坐标?

Obviously I can calculate it from various CSS properties: width, height, and so on.

显然我可以从各种 CSS 属性计算它:width, height, 等等。

I'm asking because there are many other graphical platforms that provide this as a method. For instance apparently it can be done in XUL as per this post, which describes a method getBoundingClientRect().

我问是因为有许多其他图形平台提供了这种方法。例如,显然它可以按照这篇文章在 XUL 中完成,它描述了一种方法getBoundingClientRect()

(My goal is to check whether two elements overlap.)

(我的目标是检查两个元素是否重叠。)

回答by Aletheios

Actually, there is a built-in method to get the bounding rectangle: Element.getBoundingClientRect

实际上,有一个内置的方法来获取边界矩形: Element.getBoundingClientRect

The method returns an object containing the (visual) top, right, bottom, and left coordinates of the element as well as its width and height.

该方法返回一个对象,其中包含元素的(视觉)顶部、右侧、底部和左侧坐标以及其宽度和高度。

Example (JSFiddle)

示例(JSFiddle)

More info:

更多信息:

回答by wecsam

Let's say that your DOM element had the ID myElement.

假设您的 DOM 元素具有 ID myElement

document.getElementById("myElement").offsetLeft; //Left side of box 
document.getElementById("myElement").offsetTop;  //Top side of box 
document.getElementById("myElement").offsetLeft 
    + document.getElementById("myElement").offsetWidth; //Right side of box
document.getElementById("myElement").offsetTop
    + document.getElementById("myElement").offsetHeight; //Bottom side of box 

For the bottom and right sides, the code basically adds the width or height of the bounding box to the left or top side.

对于底部和右侧,代码基本上将边界框的宽度或高度添加到左侧或顶部。

If you wanted to, you could define document.getElementById("myElement")once and use the reference, as follows:

如果您愿意,可以定义document.getElementById("myElement")一次并使用引用,如下所示:

var myElement = document.getElementById("myElement");
myElement.offsetLeft; //Left side of box 
myElement.offsetTop;  //Top side of box 
myElement.offsetLeft + myElement.offsetWidth; //Right side of box
myElement.offsetTop + myElement.offsetHeight; //Bottom side of box