2011-02-16 82 views
5

我的代碼,這一點可以在行動中可以看出這裏擴大DIV與jQuery

http://jsfiddle.net/rullingen/GCXsq/1/

上空盤旋時和合同時沒有這基本上擴展一個div高度。 目前它從75px擴展到300px。我想改變它,以便它從75px擴展到適合DIV內部內容的高度。我曾嘗試將擴展值設置爲「自動」,但這似乎不起作用。任何人都可以給我一個指針嗎?

HTML

<div class="expand"> 
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" /> 
</div> 
<div class="expand"> 
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" /> 
</div> 

<div class="expand"> 
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" /> 
</div> 

<div class="expand"> 
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" /> 
</div> 

<div class="expand"> 
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" /> 
</div> 

的Javascript

$('.expand').hover(function() { 
    $(this).animate({ 
     height: '300px' 
    }, 300); 
},function() { 
    $(this).animate({ 
     height: '75px' 
    }, 300); 
}); 

CSS

.expand { 
    overflow: hidden; 
    margin-bottom: 15px; 
    height: 75px; 
} 

回答

9

你可以計算元素的累積高度在<div>和使用結果作爲參數傳遞給animate()

$('.expand').hover(function() { 
    var contentHeight = 0; 
    $(this).children().each(function() { 
     contentHeight += $(this).height(); 
    }); 
    $(this).animate({ 
     height: contentHeight 
    }, 300); 
}, function() { 
    $(this).animate({ 
     height: '75px' 
    }, 300); 
}); 

更新提琴here

+0

非常有幫助,非常感謝。 – 2011-02-16 09:44:48

0

您可以在懸停時將樣式設置爲「display:inline-block」,並在鼠標移除時移除樣式。這適用於IE8。對於IE7 - 你可以在 (zoom:1; * display:inline; _height:30px;「)方式上加點小小的空間 - 高度可以根據您的要求進行更改