Need to find height of hidden div on page (set to display:none)

前端 未结 13 1548
萌比男神i
萌比男神i 2020-11-27 06:00

I need to measure the offsetHeight of a div that is inside of a hidden element.

相关标签:
13条回答
  • 2020-11-27 06:32

    What I wound up having to do was this:

    Using YUI 2, on page load, I found all elements of that given classname that were either set to display:none, or whose height and width was 0 (that's one way of measuring whether an element exists, or a parent is set to display:none). I then set that element to display:block. I then checked it's parent for the same thing and showed the parents until it finds a visible parent. Once highest display:none ancestor is set to display:block, I can measure my element.

    Once all elements are measured I reset all of the elements back to display:none.

    0 讨论(0)
  • 2020-11-27 06:33

    Did you try this ?

    setTimeout('alert($(".Var").height());',200); 
    
    0 讨论(0)
  • 2020-11-27 06:34

    Try to use:

    #parent{ display:block !important; visibility:hidden; position:absolute} 
    
    0 讨论(0)
  • 2020-11-27 06:36

    Until the element is rendered, it has no height. Even if you clone the parent object and display it somewhere that can't be seen by the user, there's not guarantee that the clone will have the same height as the final size of the hidden object.

    There are many things that can affect the height that wouldn't necessarily be rendered in the clone - anything in the DOM and its interaction with the CSS rules could cause a change in rendering any other element of the DOM. Short of cloning the entire document (and even that's not fool-proof) you have no way of determining the height of the hidden object.

    If you must know the height before it's displayed to the user, you'll have to "hack" it by displaying it for as short of a time as possible then hiding it again. Most likely, the user will see this hiccup and not be pleased by the result.

    0 讨论(0)
  • 2020-11-27 06:39

    You could clone the element, absolutely position it at -10000,-10000, measure the clone and destroy it.

    0 讨论(0)
  • 2020-11-27 06:43

    So here's working jQuery solution based on lod3n's answer and with help of 999's comment:

    var getHiddenElementHeight = function(element){
        var tempId = 'tmp-'+Math.floor(Math.random()*99999);//generating unique id just in case
        $(element).clone()
        .css('position','absolute')
        .css('height','auto').css('width','1000px')
        //inject right into parent element so all the css applies (yes, i know, except the :first-child and other pseudo stuff..
        .appendTo($(element).parent())
        .css('left','-10000em')
        .addClass(tempId).show()
        h = $('.'+tempId).height()
        $('.'+tempId).remove()
        return h;
    }
    

    Enjoy!

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