jQuery: Get height of hidden element in jQuery

后端 未结 14 2448
南方客
南方客 2020-11-22 09:49

I need to get height of an element that is within a div that is hidden. Right now I show the div, get the height, and hide the parent div. This seems a bit silly. Is there a

14条回答
  •  梦谈多话
    2020-11-22 10:29

    In my circumstance I also had a hidden element stopping me from getting the height value, but it wasn't the element itself but rather one of it's parents... so I just put in a check for one of my plugins to see if it's hidden, else find the closest hidden element. Here's an example:

    var $content = $('.content'),
        contentHeight = $content.height(),
        contentWidth = $content.width(),
        $closestHidden,
        styleAttrValue,
        limit = 20; //failsafe
    
    if (!contentHeight) {
        $closestHidden = $content;
        //if the main element itself isn't hidden then roll through the parents
        if ($closestHidden.css('display') !== 'none') { 
            while ($closestHidden.css('display') !== 'none' && $closestHidden.size() && limit) {
                $closestHidden = $closestHidden.parent().closest(':hidden');
                limit--;
            }
        }
        styleAttrValue = $closestHidden.attr('style');
        $closestHidden.css({
            position:   'absolute',
            visibility: 'hidden',
            display:    'block'
        });
        contentHeight = $content.height();
        contentWidth = $content.width();
    
        if (styleAttrValue) {
            $closestHidden.attr('style',styleAttrValue);
        } else {
            $closestHidden.removeAttr('style');
        }
    }
    

    In fact, this is an amalgamation of Nick, Gregory and Eyelidlessness's responses to give you the use of Gregory's improved method, but utilises both methods in case there is supposed to be something in the style attribute that you want to put back, and looks for a parent element.

    My only gripe with my solution is that the loop through the parents isn't entirely efficient.

提交回复
热议问题