how to get bounding box for div element in jquery

后端 未结 3 1449
后悔当初
后悔当初 2021-01-30 13:14

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

i tried like this .

//Left side of box 
document.getElementById(\"myElement\").of         


        
相关标签:
3条回答
  • 2021-01-30 13:23

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

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

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

    0 讨论(0)
  • 2021-01-30 13:23

    As this is specifically tagged for jQuery -

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

    or

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

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

    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...

    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...

    0 讨论(0)
  • 2021-01-30 13:45

    using JQuery:

    myelement=$("#myelement")
    [myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]
    
    0 讨论(0)
提交回复
热议问题