好吧,我要在这里回答某人关于为什么他们的脚本不起作用的问题。他们将内容加载到隐藏的 div 中,然后获取高度,以便为包裹的 div 制作动画。但我总是尝试测试我提供的代码。所以我做了this demo向他们证明这一点。
所以,嗯,我现在是进入了暮光区还是在做梦? 掐自己哎呀!
我在 Firefox、IE 和 Chrome 中尝试了该演示,两种方法都返回相同的值。 Firebug 说零!我重新启动了计算机,甚至稍微更改了代码(删除了高度函数)并尝试使用 jQuery 1.3.2,它仍然有效!我知道隐藏元素 USED 返回零值。甚至这个SO Answer正在给出我想要的建议!
所以我想我的问题是......我错过了什么还是我们提供了错误的建议?
最佳答案
查看 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 ];
}
}
关于jquery - 隐藏的 div 高度(改变我的建议),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861671/