好的,我打算在这里回答某人的问题,为什么他们的剧本不起作用。他们将内容加载到隐藏的div中,然后获得高度,以便他们可以为包装div设置动画。但我总是试着测试我提供的代码。所以我让this demo向他们证明了这一点。
所以,嗯,我进入了暮光之地还是我现在正在做梦? 捏自己 OUCH!
我在Firefox,IE和Chrome中尝试过该演示,两种方法都返回相同的值。 Firebug说零!我重新启动了我的计算机,我甚至更改了代码(删除了高度函数)并尝试使用jQuery 1.3.2并且它仍然有效!我知道隐藏元素 USED 以返回零值。即使这个SO Answer也给出了我的建议!
所以我想我的问题是......我错过了什么或者我们给出了不好的建议吗?
答案 0 :(得分:11)
查看jQuery 1.4.2和1.3.2源代码,当您在隐藏元素上调用width()
或height()
时,它实际上会自动执行此操作。它设置以下属性:
{ position: "absolute", visibility: "hidden", display:"block" }
然后获取宽度/高度,并恢复属性的旧值。
所以不需要自己更改属性--jQuery会为你处理它。
<强>&LT;编辑&gt; 强>
这将允许您获取隐藏元素的尺寸。但是,当元素包含在另一个隐藏元素中时,它将无法工作 - 您将获得高度为0.在这种情况下,您需要另一个解决方案,可能像this answer。
的&LT; /编辑&gt; 强>
以下是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 ];
}
}
答案 1 :(得分:1)
我遇到了隐藏元素宽度的同样问题,所以我写了这个插件调用jQuery Actual来修复它。而不是使用
$('#some-element').height();
使用
$('#some-element').actual('height');
将为隐藏元素提供正确的值,或者元素具有隐藏的父元素。
您也可以使用
// get hidden element actaul width
$( '.hidden' ).actual( 'width' );
// get hidden element actaul innerWidth
$( '.hidden' ).actual( 'innerWidth' );
// get hidden element actaul outerWidth
$( '.hidden' ).actual( 'outerWidth' );
// get hidden element actaul height
$( '.hidden' ).actual( 'height' );
// get hidden element actaul innerHeight
$( '.hidden' ).actual( 'innerHeight' );
// get hidden element actaul outerHeight
$( '.hidden' ).actual( 'outerHeight' );
希望这有帮助:)
答案 2 :(得分:0)
您还可以使用javascript的scrollHeight
属性。
$("#id_element").attr('scrollHeight')
答案 3 :(得分:0)
$('.hidden-element').get(0).height;
给出了DOM元素的高度,也是隐藏元素的设置