jQuery: Get height of hidden element in jQuery

后端 未结 14 2235
南方客
南方客 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:09

    One workaround is to create a parent div outside the element you want to get the height of, apply a height of '0' and hide any overflow. Next, take the height of the child element and remove the overflow property of the parent.

    var height = $("#child").height();
    // Do something here
    $("#parent").append(height).removeClass("overflow-y-hidden");
    .overflow-y-hidden {
      height: 0px;
      overflow-y: hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="parent" class="overflow-y-hidden">
      <div id="child">
        This is some content I would like to get the height of!
      </div>
    </div>

    0 讨论(0)
  • 2020-11-22 10:11

    If you've already displayed the element on the page previously, you can simply take the height directly from the DOM element (reachable in jQuery with .get(0)), since it is set even when the element is hidden:

    $('.hidden-element').get(0).height;
    

    same for the width:

    $('.hidden-element').get(0).width;
    

    (thanks to Skeets O'Reilly for correction)

    0 讨论(0)
  • 2020-11-22 10:12

    You are confuising two CSS styles, the display style and the visibility style.

    If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.

    If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.

    0 讨论(0)
  • 2020-11-22 10:12

    Building further on Nick's answer:

    $("#myDiv").css({'position':'absolute','visibility':'hidden', 'display':'block'});
    optionHeight = $("#myDiv").height();
    $("#myDiv").css({'position':'static','visibility':'visible', 'display':'none'});
    

    I found it's better to do this:

    $("#myDiv").css({'position':'absolute','visibility':'hidden', 'display':'block'});
    optionHeight = $("#myDiv").height();
    $("#myDiv").removeAttr('style');
    

    Setting CSS attributes will insert them inline, which will overwrite any other attributes you have in your CSS file. By removing the style attribute on the HTML element, everything is back to normal and still hidden, since it was hidden in the first place.

    0 讨论(0)
  • 2020-11-22 10:14

    Here's a script I wrote to handle all of jQuery's dimension methods for hidden elements, even descendants of hidden parents. Note that, of course, there's a performance hit using this.

    // Correctly calculate dimensions of hidden elements
    (function($) {
        var originals = {},
            keys = [
                'width',
                'height',
                'innerWidth',
                'innerHeight',
                'outerWidth',
                'outerHeight',
                'offset',
                'scrollTop',
                'scrollLeft'
            ],
            isVisible = function(el) {
                el = $(el);
                el.data('hidden', []);
    
                var visible = true,
                    parents = el.parents(),
                    hiddenData = el.data('hidden');
    
                if(!el.is(':visible')) {
                    visible = false;
                    hiddenData[hiddenData.length] = el;
                }
    
                parents.each(function(i, parent) {
                    parent = $(parent);
                    if(!parent.is(':visible')) {
                        visible = false;
                        hiddenData[hiddenData.length] = parent;
                    }
                });
                return visible;
            };
    
        $.each(keys, function(i, dimension) {
            originals[dimension] = $.fn[dimension];
    
            $.fn[dimension] = function(size) {
                var el = $(this[0]);
    
                if(
                    (
                        size !== undefined &&
                        !(
                            (dimension == 'outerHeight' || 
                                dimension == 'outerWidth') &&
                            (size === true || size === false)
                        )
                    ) ||
                    isVisible(el)
                ) {
                    return originals[dimension].call(this, size);
                }
    
                var hiddenData = el.data('hidden'),
                    topHidden = hiddenData[hiddenData.length - 1],
                    topHiddenClone = topHidden.clone(true),
                    topHiddenDescendants = topHidden.find('*').andSelf(),
                    topHiddenCloneDescendants = topHiddenClone.find('*').andSelf(),
                    elIndex = topHiddenDescendants.index(el[0]),
                    clone = topHiddenCloneDescendants[elIndex],
                    ret;
    
                $.each(hiddenData, function(i, hidden) {
                    var index = topHiddenDescendants.index(hidden);
                    $(topHiddenCloneDescendants[index]).show();
                });
                topHidden.before(topHiddenClone);
    
                if(dimension == 'outerHeight' || dimension == 'outerWidth') {
                    ret = $(clone)[dimension](size ? true : false);
                } else {
                    ret = $(clone)[dimension]();
                }
    
                topHiddenClone.remove();
                return ret;
            };
        });
    })(jQuery);
    
    0 讨论(0)
  • 2020-11-22 10:15

    Following Nick Craver's solution, setting the element's visibility allows it to get accurate dimensions. I've used this solution very very often. However, having to reset the styles manually, I've come to find this cumbersome, given that modifying the element's initial positioning/display in my css through development, I often forget to update the related javascript code. The following code doesn't reset the styles per say, but removes the inline styles added by javascript:

    $("#myDiv")
    .css({
        position:   'absolute',
        visibility: 'hidden',
        display:    'block'
    });
    
    optionHeight = $("#myDiv").height();
    optionWidth = $("#myDiv").width();
    
    $("#myDiv").attr('style', '');
    

    The only assumption here is that there can't be other inline styles or else they will be removed aswell. The benefit here, however, is that the element's styles are returned to what they were in the css stylesheet. As a consequence, you can write this up as a function where an element is passed through, and a height or width is returned.

    Another issue I've found of setting the styles inline via js is that when dealing with transitions through css3, you become forced to adapt your style rules' weights to be stronger than an inline style, which can be frustrating sometimes.

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