jQuery Jquery获取隐藏元素的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9117738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery getting a hidden element's height
提问by Malixxl
I was trying to get a list of element's height value but it was returning 0.
I've done some research and saw that in order get element's height, that element must be visible.
But I want to check its height when it's hidden. If its height is bigger than some value use some functions then make it visible. Is there any way to do this?
我试图获取元素高度值的列表,但它返回 0。
我做了一些研究,看到为了获取元素的高度,该元素必须是可见的。
但是我想在它隐藏时检查它的高度。如果它的高度大于某个值,请使用一些函数然后使其可见。有没有办法做到这一点?
I mean:
我的意思是:
- Check hidden element's height.
- If it has OK value make it visible.
- If it doesn't have required value do some functions.
- Make it visible.
- 检查隐藏元素的高度。
- 如果它具有 OK 值,则使其可见。
- 如果它没有所需的值,请执行一些功能。
- 使其可见。
回答by ShankarSangoli
You can show
the element get the height and then hide it, visually you will not see any difference.
你可以show
让元素获取高度然后隐藏它,视觉上你不会看到任何区别。
var height = $('elementSelector').show().height();
$('elementSelector').hide();
if(height != <<HeightToCompare>>){
//Code here
}
//Finally make it visible
$('elementSelector').show();
回答by Ken Redler
One way is to clone the object, position the clone far outside the viewport, make it visible, measure the clone, then destroy it.
一种方法是克隆对象,将克隆放置在视口之外的远处,使其可见,测量克隆,然后销毁它。
So you have:
所以你有了:
<div id="maybe" style="display: none;">
Something
</div>
Since you're using jQuery, you'd do something like this:
由于您使用的是 jQuery,您可以执行以下操作:
$('#maybe')
.clone()
.attr('id','maybe_clone') // prevent id collision
.css({ // position far outside viewport
'position': 'absolute',
'left': '-1000px'
});
if( $('#maybe_clone').show().height() > 200 ) {
$('#maybe').show();
}
$('#maybe_clone').remove(); // housekeeping
回答by Nathan Hase
Position the object so it is visible to the browser, but not the user: jQuery: Get height of hidden element in jQuery
定位对象使其对浏览器可见,但对用户不可见: jQuery: Get height of hidden element in jQuery