jQuery 如何在jquery中获取div元素的边界框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18780139/
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-08-26 22:30:33  来源:igfitidea点击:

how to get bounding box for div element in jquery

javascriptjqueryhtmlcsssvg

提问by SivaRajini

i want to calculate bounding box for div element via jquery/javascript.

我想通过 jquery/javascript 计算 div 元素的边界框。

i tried like this .

我试过这样。

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

it returns some values. whether it is correct way to get bounding box for div element via jquery / javascript.

它返回一些值。通过jquery / javascript.

i need something like getBBox()method in SVGelement. it will return x,y ,width and height of an element. sameway how can i get bounding box for div element.

我需要元素中的getBBox()方法之类的 东西SVG。它将返回元素的 x,y ,width 和 height。同样,我如何获得 div 元素的边界框。

Thanks,

谢谢,

Siva

湿婆

回答by Rycochet

As this is specifically tagged for jQuery -

因为这是专门为 jQuery 标记的 -

$("#myElement")[0].getBoundingClientRect();

or

或者

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get()was slightly faster)

(这些在功能上是相同的,在一些较旧的浏览器.get()中速度稍快一些)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

请注意,如果您尝试通过 jQuery 调用获取值,则它不会考虑任何 css 转换值,这可能会产生意想不到的结果......

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

注 2:在 jQuery 3.0 中,它已更改getBoundingClientRect()为对自己的维度调用使用正确的调用(请参阅jQuery Core 3.0 升级指南)——这意味着其他 jQuery 答案最终将始终正确——但仅当使用新的 jQuery 版本时- 因此,为什么它被称为突破性的变化......

回答by Robert Longson

You can get the bounding box of any element by calling getBoundingClientRect

您可以通过调用getBoundingClientRect获取任何元素的边界框

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

这将返回一个带有左、上、宽和高字段的对象。

回答by Arpit Agrawal

using JQuery:

使用 JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]