jQuery: Get height of hidden element in jQuery

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

    Building further on user Nick's answer and user hitautodestruct's plugin on JSBin, I've created a similar jQuery plugin which retrieves both width and height and returns an object containing these values.

    It can be found here: http://jsbin.com/ikogez/3/

    Update

    I've completely redesigned this tiny little plugin as it turned out that the previous version (mentioned above) wasn't really usable in real life environments where a lot of DOM manipulation was happening.

    This is working perfectly:

    /**
     * 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 
     * @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 = $("
    ").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; };

提交回复
热议问题