【问题标题】:How to Set Dynamic Height jQuery如何设置动态高度 jQuery
【发布时间】:2015-01-26 04:00:32
【问题描述】:

我有多个具有相同类名的父 div,一个是父 div,另一个是子 div。

 <div class="container" style="height:150px; width:50%;">
    <div class="overlay"></div>
 </div>

 <div class="container" style="height:250px; width:50%;">
    <div class="overlay"></div>
 </div>


 <div class="container" style="height:350px; width:50%;">
    <div class="overlay"></div>
 </div>

我想设置覆盖 div 高度等于容器 div 高度,我面临的问题是每个容器 div 都有不同的高度,我无法找出如何设置每个覆盖 div 高度等于它的父容器div 高度。

我正在使用以下 jquery 代码为每个设置叠加高度

$(".container").each(function(){
    $(".overlay").height($(".container").height());
});

以上代码仅获取第一个容器的高度,并将所有覆盖 div 的高度设置为第一个容器。我的意思是它在所有覆盖 div 中设置 height:150px,我想设置覆盖 div 高度等于其父容器 div。

<div class="container" style="height:150px; width:50%;">
    <div class="overlay" style="height:150px;"></div>
 </div>

 <div class="container" style="height:250px; width:50%;">
    <div class="overlay" style="height:150px;"></div>
 </div>


 <div class="container" style="height:350px; width:50%;">
    <div class="overlay" style="height:150px;"></div>
 </div>

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你可以这样做:

    $(".overlay").each(function(){
        $(this).height($(this).parent().height());
    });
    

    【讨论】:

      【解决方案2】:

      选择器$(".container").height() 返回一个容器列表,并从列表中获取第一个容器的高度。
      因此,当您设置$(".overlay").height($(".container").height()) 时,您会将所有子元素设置为第一个容器的高度。

      您需要遍历所有子容器,并将它们的高度分别设置为它们的容器。它可以使用代表当前子元素的$(this) 关键字来实现,并使用它的.parent() 来实现,这将返回其各自的容器父元素。

      $(".overlay").each(function(){
          $(this).height($(this).parent().height());
      });
      

      【讨论】:

        【解决方案3】:

        在样式表中将 overlay 高度设置为 100%:

        .overlay {
          height: 100%;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-18
          • 1970-01-01
          • 1970-01-01
          • 2015-08-13
          • 2013-06-02
          • 1970-01-01
          相关资源
          最近更新 更多