How to get the min-height of the object when its parent is set to display none?

假装没事ソ 提交于 2019-12-10 19:38:11

问题


Why I can't get the min-height of an object when its parent is set to display: none, but I still can it the object's height if the min-height is not in use?

For instance,

css,

li {
display:none;
}

.object {
display:block;
width:100px;
border:1px solid #000;
}

html,

<li><a href="#" class="object" style="height:200px;"><img class="element" /></a></li>
<li><a href="#" class="object" style="min-height:300px;"><img class="element" /></a></li>

jquery,

$(document).ready(function(){

    $('.object img').each(function(){
        alert($(this).parent().height());
    });

});

jsfiddle

How can I still get the min-height of the object even though its parent is set to display none?


回答1:


When an element isn't displayed, it has no height or width.

You can extract the CSS attribute, though:

alert($(this).parent().css('min-height'));

http://jsfiddle.net/R5SDY/1/

Note that this now returns a string with "px" at the end, instead of a number like height() does. You may need to parse it as an integer:

alert( parseInt($(this).parent().css('min-height'),10) );

Obviously if there's no min-height set in CSS, this won't work. Depending on what you want the number for, you may need to add some programmatic logic that extracts .css('height') if there's no min-height returned.

$(document).ready(function(){    
    $('.object img').each(function(){
        var h = parseInt($(this).parent().css('min-height'),10) 
            || parseInt($(this).parent().css('height'),10);
        alert(h);
    });
});
​

http://jsfiddle.net/R5SDY/2/

Finally, remember that the values you're getting from .css aren't necessarily what the height will be when the element is finally displayed -- they're only what you want the height to be.




回答2:


$('.object img').each(function(){
    alert($(this).parent().css("min-height"));
});

that is just to get the css attribute, a hidden object has no height or width, so you'll need to display it, get the measurments and hide it.

something like the following: http://jsfiddle.net/c2vrr/

please note that aslong as your DOM isn't 'huge' - it'll be instantanous, and you won't see the 'briefly displayed' elements.



来源:https://stackoverflow.com/questions/9773673/how-to-get-the-min-height-of-the-object-when-its-parent-is-set-to-display-none

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!