相对定位的div根据内容调整绝对定位的div高度

4

我有一个绝对定位的 div 在相对定位的 div 内部。

我需要父级相对定位的 div 调整大小以适应绝对定位 div 的大小(这是动态更改的,取决于它在哪个页面上)

我已经阅读了可以使用 jQuery 完成此操作,但我无法使其正常工作。

以下是我的代码...

Html

 <div class="product-view">
<div style="float:left;">Product Image</div>
 <div class="product-shop">
<div id="mm_grid_wrapper">
<table>dynamic content</table>
</div>

CSS...

    .product-view {
    margin-top: 5px;
    border: 1px solid #cecece;
    padding: 22px 0 0 0;
    position: relative;
    bottom:0px;


}
.product-view .product-shop {
    text-align: left;
    width: 48%;
    float: left;/*max-width: 329px;*/
}

    #mm_grid_wrapper{
position:absolute;
left:10px;
margin:0 310px 0 0;
max-width: 1630px;
top:0;
height:100%;
}


}

javascript...

$(function()
{
    $('.product-view') .css({'height': (($('#mm_grid_wrapper').height()) + 20)+'px'});

    $('#mm_grid_wrapper').bind('resize', function(){
        $('.product-view') .css({'height': (($('#mm_grid_wrapper').height()) +20)+'px'});
             });
});

1
难道不能将mm_grid_wrapper设置为相对定位吗?这样父元素就会根据其大小自动调整大小。 - sroes
@sroes,实际上我的HTML有点问题...我已经修改了。否则它会缩小到包装div的大小,所以必须是绝对的。 - user1475110
1个回答

0
  1. 从你的CSS中删除“bottom:0px;”在product-view类,它会破坏你的HTML。

  2. 尝试将你的jQuery代码放在DOM准备监听器中:

     $(document).ready(function(){
        $('.product-view') .css({'height': (($('#mm_grid_wrapper').height()) + 20)+'px'});
    
        $('#mm_grid_wrapper').bind('resize', function(){
          $('.product-view') .css({'height': (($('#mm_grid_wrapper').height()) +20)+'px'});
         });
     });
    
  3. 使用jQuery中的“resize()”和“height()”函数,这样你的最终代码将像这样:

         $(document).ready(function(){
        $('.product-view').height($('#mm_grid_wrapper').height() + 20);
    
        $('#mm_grid_wrapper').resize(function(){
          $('.product-view').height($('#mm_grid_wrapper').height() + 20);
         });
     });
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接