Using Javascript or HTML, how to get the height and width of a div or other element?

后端 未结 4 970
失恋的感觉
失恋的感觉 2021-01-25 21:32

I\'ve been trying for a while now to \'get\' the height and width of a div on my webpage. I\'ve tried many things, some are:

document.getElementById(\"header\").         


        
相关标签:
4条回答
  • 2021-01-25 22:01

    to get height use

    document.getElementById("header").offsetHeight
    

    and for width use

    document.getElementById("header").offsetWidth;
    
    0 讨论(0)
  • 2021-01-25 22:02

    example -

    var divheight = document.getElementById('divId').offsetHeight;
    

    refer this -

    http://www.w3schools.com/jsref/dom_obj_all.asp

    0 讨论(0)
  • 2021-01-25 22:19

    You should think about getting jQuery, as then you can just this and more very easily:

    $("#header").width(); // Gets the width;
    $("#header").width(50); // Set width to 50;
    $("#header").height(); // Gets the height;
    $("#header").height(50); // Set height to 50;
    

    It'll make your life a lot easier in the long run too. Writing with native Javascript can be cumbersome as it requires more code and lots of cross browser testing.

    0 讨论(0)
  • 2021-01-25 22:21

    if you don't use jQuery try this:

    document.getElementById('someDiv').clientHeight;
    document.getElementById('someDiv').offsetHeight;
    document.getElementById('someDiv').scrollHeight;
    

    Depend what you need.

    0 讨论(0)
提交回复
热议问题