【问题标题】:How to get the min-height of the object when its parent is set to display none?当其父对象设置为不显示时,如何获取对象的最小高度?
【发布时间】:2012-04-04 03:29:00
【问题描述】:

为什么当对象的 parent 设置为 display: none 时,我无法获取对象的 min-height,但如果 min-height 为 ,我仍然可以获取对象的高度没有在使用中?

例如,

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

即使其父对象设置为display none,我如何仍能获得对象的min-height

【问题讨论】:

    标签: jquery each css


    【解决方案1】:

    当一个元素不显示时,它没有高度或宽度。

    不过,您可以提取 CSS 属性:

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

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

    请注意,这现在返回一个以“px”结尾的字符串,而不是像height() 那样的数字。您可能需要将其解析为整数:

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

    显然,如果 CSS 中没有设置 min-height,这将不起作用。根据您想要的数字,您可能需要添加一些编程逻辑,如果没有返回最小高度,则提取 .css('height')

    $(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/

    最后,请记住,您从.css 获得的值不一定是元素最终显示时的高度——它们只是您想要的高度成为。

    【讨论】:

    • 如果最小高度在 em 中,而不是在 px 中,它的工作方式是否相同?
    • @Pierre-OlivierVares 当然,但您可能需要将其转换为像素,具体取决于您对它的处理方式。
    【解决方案2】:
    $('.object img').each(function(){
        alert($(this).parent().css("min-height"));
    });
    

    这只是为了获取 css 属性,隐藏的对象没有高度或宽度,所以你需要显示它,获取测量值并隐藏它。

    类似于以下内容: http://jsfiddle.net/c2vrr/

    请注意,只要您的 DOM 不是“巨大”的 - 它是即时的,您不会看到“短暂显示”的元素。

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 2019-08-30
      • 2021-02-14
      • 2017-11-23
      • 2012-10-10
      相关资源
      最近更新 更多