Get the bounding box of a div element: jQuery implementation method
P粉207483087
P粉207483087 2023-08-22 11:18:36
0
2
473
<p>I want to calculate the bounding box of a div element via jQuery/JavaScript. </p> <p>I tried the following code: </p> <pre class="brush:php;toolbar:false;">//The left side of the box document.getElementById("myElement").offsetLeft; //Top of the box document.getElementById("myElement").offsetTop; //right side of the box document.getElementById("myElement").offsetLeft document.getElementById("myElement").offsetWidth; //bottom of the box document.getElementById("myElement").offsetTop document.getElementById("myElement").offsetHeight;</pre> <p>It returns some value. Is this the correct way to get the bounding box of a div element via jQuery/JavaScript. </p> <p>I need something similar to the <code>getBBox()</code> method in the SVG element. It will return the <code>x</code>, <code>y</code>, <code>width</code>, and <code>height</code> of the element. Likewise, how do I get the bounding box of a div element? </p>
P粉207483087
P粉207483087

reply all(2)
P粉360266095

Since this is specifically marked for jQuery -

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

or

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

(The two are functionally the same, in some older browsers, .get() is slightly faster)

Please note that if you try to get the value via a jQuery call, it will not take into account any css transform values, which may lead to unexpected results...

Note 2: In jQuery 3.0, it has been changed to use the appropriate getBoundingClientRect() call to make its own size calls (see jQuery Core 3.0 Upgrade Guide) - This means that the other jQuery answers will eventually always be correct - but only when using new jQuery versions - which is why it's called a breaking change...

P粉649990273

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

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

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!