How do you get the rendered height of an element?

前端 未结 18 2343
情书的邮戳
情书的邮戳 2020-11-22 03:11

How do you get the rendered height of an element?

Let\'s say you have a

element with some content inside. This content inside is going to st
18条回答
  •  青春惊慌失措
    2020-11-22 03:36

    Definitely use

    $('#someDiv').height()   // to read it
    

    or

    $('#someDiv').height(newHeight)  // to set it
    

    I'm posting this as an additional answer because theres a couple important things I just learnt.

    I almost fell into the trap just now of using offsetHeight. This is what happened :

    • I used the good old trick of using a debugger to 'watch' what properties my element has
    • I saw which one has a value around the value I was expecting
    • It was offsetHeight - so I used that.
    • Then i realized it didnt work with a hidden DIV
    • I tried hiding after calculating maxHeight but that looked clumsy - got in a mess.
    • I did a search - discovered jQuery.height() - and used it
    • found out height() works even on hidden elements
    • just for fun I checked the jQuery implementation of height/width

    Here's just a portion of it :

    Math.max(
    Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
    Math.max(document.body["offset" + name], document.documentElement["offset" + name])
    ) 
    

    Yup it looks at BOTH scroll and offset. If that fails it looks even further, taking into account browser and css compatibility issues. In other words STUFF I DONT CARE ABOUT - or want to.

    But I dont have to. Thanks jQuery!

    Moral of the story : if jQuery has a method for something its probably for a good reason, likely related to compatibilty.

    If you haven't read through the jQuery list of methods recently I suggest you take a look.

提交回复
热议问题