查看 jQuery 1.4.2 和 1.3.2 源代码,当您在隐藏元素上调用 width() 或 height() 时,它实际上会自动执行此操作。它设置以下属性:
{ position: "absolute", visibility: "hidden", display:"block" }
然后它获取宽度/高度,并恢复属性的旧值。
因此无需自己更改属性 - jQuery 会为您处理。
这将允许您获取隐藏元素的尺寸。但是,当元素包含在另一个隐藏元素中时,它将不起作用 - 您将获得 0 的高度。在这种情况下,您需要另一个解决方案,可能像 this answer。
编辑>
以下是 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 ];
}
}