2011-10-13 72 views
0

我已經創建了一個幻燈片圖像的腳本。每個圖像都包含在「幻燈片」格中。我想要做的是垂直對齊每個單獨的圖像使用jQuery。目前我使用:如何使用jQuery將不同高度的多個圖像垂直對齊?

$('.slide img').each(function() { 
    var image_height = $(this).height(); 
    var height_margin = (image_height/2)*-1; 
    $('.slide img').css('margin-top', height_margin); 
    $('.slide img').css('top', 50%);  
    $('.slide img').css('height', image_height);  

}); 

我已經注意到的是,它適用於從第一圖像的第一高度和利潤率爲ALL的<div class"slide"></div>標籤。另外:<div class"slide"></div>具有600px的恆定高度。

不是每個圖像都是一樣的,我希望它是動態的...任何想法?

回答

0

您不應該在.each循環內使用$('.slide img'),因爲此選擇器將更改所有樣式。目前,您正在將最後一張圖片的設置應用於所有圖片。代碼中的另一個錯誤:您忘記引用50%

$('.slide img').each(function() { 
    var $this = $(this); 
    var image_height = $this.height(); 
    var height_margin = (image_height/2)*-1; 
    $this.css('margin-top', height_margin); 
    $this.css('top', '50%');  
    $this.css('height', image_height);  
}); 

您的代碼可以優化甚至更多:

$('.slide img').each(function() { 
    var $this = $(this); 
    var image_height = $this.height(); 
    var height_margin = -image_height/2 
    $this.css({'margin-top', height_margin, 
       'top', '50%', 
       'height', image_height 
       });  
}); 
0

如果​​容器具有恆定的高度,你可以申請display:blockmargin:auto 0;.slide img在CSS來達到同樣的效果......不需要JS計算。

0

好,我有一個解決方案,首先使含DIV的line-height的最高圖像高度一致,然後在課堂上使用vertical-align:middle你適用於所有圖像,請確保圖像設置爲display:inline雖然或它不會工作。

div.container {line-height:300px;} /*or whatever that may be, then*/ 
img.slides {vertical-align:middle;}