我需要得到一个元素的高度,在一个div是隐藏的。现在我显示div,获得高度,并隐藏父div。这看起来有点傻。有没有更好的办法?

我使用jQuery 1.4.2:

$select.show();
optionHeight = $firstOption.height(); //we can only get height if its visible
$select.hide();

当前回答

您还可以使用负边距将隐藏的div定位到屏幕之外,而不是使用display:none,很像文本缩进图像替换技术。

eg.

position:absolute;
left:  -2000px;
top: 0;

这样,height()仍然可用。

其他回答

如果你之前已经在页面上显示了元素,你可以直接从DOM元素中获取高度(在jQuery中可以通过.get(0)获得),因为即使在元素隐藏时它也会被设置:

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

宽度也一样:

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

(感谢Skeets O'Reilly的更正)

实际上,我有时会使用一些技巧来处理这个问题。我开发了一个jQuery滚动条小部件,在那里我遇到了一个问题,我不知道可滚动的内容是否是隐藏标记的一部分。以下是我所做的:

// try to grab the height of the elem
if (this.element.height() > 0) {
    var scroller_height = this.element.height();
    var scroller_width = this.element.width();

// if height is zero, then we're dealing with a hidden element
} else {
    var copied_elem = this.element.clone()
                      .attr("id", false)
                      .css({visibility:"hidden", display:"block", 
                               position:"absolute"});
    $("body").append(copied_elem);
    var scroller_height = copied_elem.height();
    var scroller_width = copied_elem.width();
    copied_elem.remove();
}

这在很大程度上是可行的,但有一个明显的问题可能会出现。如果要克隆的内容使用CSS样式,其中包含在规则中引用父标记,那么克隆的内容将不包含适当的样式,并且可能具有略微不同的度量。要解决这个问题,您可以确保要克隆的标记应用了CSS规则,这些规则不包括对父标记的引用。

另外,我的滚动部件没有出现这种情况,但是为了获得克隆元素的适当高度,您需要将宽度设置为与父元素相同的宽度。在我的例子中,CSS宽度总是应用于实际的元素,所以我不必担心这一点,但是,如果元素没有应用宽度,您可能需要对元素的DOM祖先进行某种递归遍历,以找到适当的父元素的宽度。

下面是我编写的一个脚本,用于处理隐藏元素的所有jQuery维度方法,甚至是隐藏父元素的后代。当然,请注意,使用这种方法会影响性能。

// 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);

在用户Nick的回答和用户hitautodestruct的JSBin插件的基础上,我创建了一个类似的jQuery插件,它检索宽度和高度,并返回一个包含这些值的对象。

可以在这里找到: http://jsbin.com/ikogez/3/

更新

我已经完全重新设计了这个小插件,因为原来的版本(上面提到的)在现实生活环境中并不能真正使用,因为那里发生了很多DOM操作。

这是完美的:

/**
 * getSize plugin
 * This plugin can be used to get the width and height from hidden elements in the DOM.
 * It can be used on a jQuery element and will retun an object containing the width
 * and height of that element.
 *
 * Discussed at StackOverflow:
 * http://stackoverflow.com/a/8839261/1146033
 *
 * @author Robin van Baalen <robin@neverwoods.com>
 * @version 1.1
 * 
 * CHANGELOG
 *  1.0 - Initial release
 *  1.1 - Completely revamped internal logic to be compatible with javascript-intense environments
 *
 * @return {object} The returned object is a native javascript object
 *                  (not jQuery, and therefore not chainable!!) that
 *                  contains the width and height of the given element.
 */
$.fn.getSize = function() {    
    var $wrap = $("<div />").appendTo($("body"));
    $wrap.css({
        "position":   "absolute !important",
        "visibility": "hidden !important",
        "display":    "block !important"
    });

    $clone = $(this).clone().appendTo($wrap);

    sizes = {
        "width": $clone.width(),
        "height": $clone.height()
    };

    $wrap.remove();

    return sizes;
};

您还可以使用负边距将隐藏的div定位到屏幕之外,而不是使用display:none,很像文本缩进图像替换技术。

eg.

position:absolute;
left:  -2000px;
top: 0;

这样,height()仍然可用。