Hidden div height (changing my advice)

后端 未结 4 1676
一向
一向 2021-01-02 15:54

Ok, I was going to answer someone\'s question here on SO about why their script wasn\'t working. They loaded content into a hidden div, then got the height so they could ani

4条回答
  •  被撕碎了的回忆
    2021-01-02 16:18

    Looking at the jQuery 1.4.2 and 1.3.2 source code, it actually performs this automatically when you call width() or height() on a hidden element. It sets the following attributes:

    { position: "absolute", visibility: "hidden", display:"block" }
    

    Then it gets the width/height, and restores the old values of the attributes.

    So there is no need to change the attributes yourself - jQuery will handle it for you.


    This will allow you to get the dimensions of a hidden element. However, it won't work when the element is contained within another hidden element - you'll get a height of 0. In that case you'd need another solution, possibly like this answer.


    Here are the relevant bits of the source code from 1.4.2:

    cssShow = { position: "absolute", visibility: "hidden", display:"block" },
    
    //[undocumented jQuery.css function which is called by .height() and .width()]
    css: function( elem, name, force, extra ) {
        if ( name === "width" || name === "height" ) {
            var val, props = cssShow, ....
    
            function getWH() {
                ... this function gets the actual width/height into the variable val
            }
    
            if ( elem.offsetWidth !== 0 ) {
                getWH();
            } else {
                jQuery.swap( elem, props, getWH );
            }
    
            return Math.max(0, Math.round(val));
        }
        return jQuery.curCSS( elem, name, force );
    },
    
    // A method for quickly swapping in/out CSS properties to get correct calculations
    swap: function( elem, options, callback ) {
        var old = {};
    
        // Remember the old values, and insert the new ones
        for ( var name in options ) {
            old[ name ] = elem.style[ name ];
            elem.style[ name ] = options[ name ];
        }
    
        callback.call( elem );
    
        // Revert the old values
        for ( var name in options ) {
            elem.style[ name ] = old[ name ];
        }
    }
    

提交回复
热议问题