2011-07-30 66 views
0

我有一個幻燈片放映在容器中運行,需要容器的高度以匹配可見幻燈片的高度。不幸的是,圖像是絕對定位的,我無能爲力。爲了解決這個問題,我使用了一點jQuery魔術來照顧相同的功能。使用jQuery調整父元素的高度以匹配其可見子元素的高度

由於某些原因,我的代碼無法正常工作。每當#container元素被調整大小時,該函數運行並且是假定#main的高度調整爲與可見幻燈片相同的值。

但是,呃..沒有bueno。在我的控制檯中不顯示任何錯誤。思考?

http://jsfiddle.net/danielredwood/2G4ky/3/

幻燈片插件:http://jquery.malsup.com/cycle/

HTML:

<div id="container"> 
    <div id="main" class="home" role="main"> 
     <img class="slide" src="http://payload.cargocollective.com/1/0/18788/1279362/452120_800_892531_800.jpg" /> 
     <img class="slide" src="http://payload.cargocollective.com/1/0/18788/1279362/452125_800_37eba7_800.jpg" /> 
     <img class="slide" src="http://payload.cargocollective.com/1/0/18788/1279362/452132_800_7dc0b6_800.jpg" /> 
    </div> 
</div> 

CSS:

#container { 
    max-width:960px; 
} 
#main { 
    max-width:780px; 
    height:520px; 
    margin:0 auto 40px; 
    overflow:hidden; 
    background:#ccc; 
} 
#main img { 
    width:100%; 
    height:auto; 
} 

的JavaScript:

$('.home').cycle({ 
    fx:'fade' 
}); 
$('#container').resize(function(){ 
     var child_height = $('.slide:visible').height(); 
     $('#main').css('height', child_height); 
}); 
+0

兩件事情:你應該包括在問題的代碼,創建它可以幫助別人的問題的永久記錄未來。第二件事是你有一個糟糕的圖像選擇 - 人們在工作時解決了stackoverflow的問題,這不是我希望其他人在我的顯示器上看到的圖像。 –

+0

此外,@ Andrew的評論:如果您使用插件*指定*,並*鏈接到*,插件,在您的問題。它減少了我們不得不花費的時間來幫助你。 –

+0

@Andrew Shepherd - 用適當的代碼更新了問題。謝謝你的領導。 – technopeasant

回答

1

代替之前或幻燈片後回調運行,作爲窗口調整其大小,縮放圖像。完善!

$(window).resize(function() { 
    $('#main').css('height',$('img.slide:visible').height()); 
}); 
3

我建議使用插件的回調辦法,特別是after

$('.home').cycle({ 
    fx:'fade', 
    after: function(){ 
     $('#main').css('height',$(this).outerHeight()); 
    } 
}); 

Updated JS Fiddle demo

參考文獻:

+0

欣賞答案..沒有達到我在找什麼。我不想調整圖片的高度,而是調整其父母#main以匹配圖片的高度。所以......翻轉。 – technopeasant

+0

它不調整圖像的高度。 '$(this).outerHeight()'檢索圖像的高度,並將該高度賦值給'$('#main')'元素。 –

+0

哦,對,我之前沒有意識到,因爲它在幻燈片間隔調整。我正在尋找連續的,瞬間的,這就是爲什麼我在我所走過的路上徘徊。 – technopeasant

0

我發現這工作得很好:

$(window).load(function() { 
var imageHeight = $(".image-box img").height(); 
$(".image-box img").parent().css('height', imageHeight); 
}); 

$(window).resize(function() { 
var imageHeight2 = $(".image-box img").height(); 
$(".image-box img").parent().css('height', imageHeight2); 
}); 

其中「圖像配箱」是爲您的圖像容器。

我也添加到了我的CSS的響應:

.image-box img{ 
max-width: 100%; 
height:auto !important; 

}