如何在不指定高度的情况下覆盖div的所有内部元素

时间:2014-04-10 21:51:50

标签: jquery css

如何处理div的高度以覆盖所有内部元素?我的div中的元素数量没有提前指定并且不断变化,所以如何在下面的示例中处理高度?

$('#item1').hover(function(){

 $("#spec1").stop(true).animate({height:'100px'}, 300);
},function(){
$("#spec1").stop(true).animate({height:'0px'}, 300);
})

换句话说,我不知道我的div的确切高度来覆盖内部元素;我该如何处理这个问题?

Fiddle

4 个答案:

答案 0 :(得分:1)

我认为你应该在每次元素数量变化时捕获,然后根据它重新计算高度。

$("#SomeContainer").change(function(){
   var newHeight = $("#SomeContainer").height();
   $("#spec1").height(newHeight);
 });

答案 1 :(得分:0)

尝试这样的事情

    $('#item1').hover(function(){
    var height = $("#spec1").children().length * 20;

     $("#spec1").stop(true).animate({height:height}, 300);
     },function(){
     $("#spec1").stop(true).animate({height:'0px'}, 300);
      })

答案 2 :(得分:0)

你可以简单地做到这一点

<div id='item1'>
   Item 1
 </div>
<div id='spec1'>
<div id="container">
    sepc 1
    <br/>
    sepc 2
    <br/>
    sepc 3
    <br/>
    sepc 4
    <br/>
  </div>
</div>

的javascript

  $('#item1').hover(function(){
      $("#spec1").stop(true).animate({height: $("#prova").height()+"px"}, 300);
  },function(){
     $("#spec1").stop(true).animate({height:'0px'}, 300);
  })

答案 3 :(得分:0)

animate()中将高度设置为100%,它会随着div的高度而变化。

$('#item1').hover(function(){
    $("#spec1").stop(true).animate({height:'100%'}, 300);
},function(){
    $("#spec1").stop(true).animate({height:'0px'}, 300);
})

请参阅Fiddle


<强>已更新

我的原始答案仅在父元素具有固定高度时才有效。

如果您不太习惯使用animate(),则可以改为使用slideDown() / slideUp()

$('#item1').hover(function () {
    $("#spec1").stop(true).slideDown(300);
}, function () {
    $("#spec1").stop(true).slideUp(300);
}) 

#spec1的CSS也必须略有改变。删除height: 0并使用display: none也会隐藏div,直到将其悬停。你已经在CSS中注释了这个,所以我只是取消注释它:

#spec1 {
    background-color:red;
    width:120px;
    display:none;
    text-align: center;
    /*height:0px;*/
    overflow:hidden;
}

我已更新Fiddle

相关问题