2014-08-29 81 views
0

我有一個響應div(.container),它包含一行嵌套的div(.imgWrapper),每行包含一個圖像(.imgWrapper img)。下面的代碼的目的是使所有圖像相同的高度,而在一排仍安裝在容器中,儘管所有的圖像是不同的比例彼此(即橫向和縱向)使用jQuery使一個函數在同一個類中工作

var totalHeight = 100; 
var totalWidth = 1; 
$('.imgWrapper').each(function(){ 
totalWidth += $(this).outerWidth(); 
}); 

var containerWidth = $('.container').width(); 
var ratio = totalWidth/totalHeight; 
var containerHeight = containerWidth/ratio; 

$('.container').css('height',containerHeight + "px"); 
$('.imgWrapper img').css('height',containerHeight + "px"); 

var newTotalWidth = 0; 
$('.imgWrapper').each(function(){ 
newTotalWidth += $(this).outerWidth(); 
}); 

$('.container').css('width',newTotalWidth + "px"); 

}); 

}); 

這一切的偉大工程如果只有一個帶有「.container」類的div,但是隻要我在同一個類中添加div,該函數就會應用於所有圖像,而不是每個「.container」div中的圖像。如何將這個函數應用於每個'.container'div?

這裏是一個jsfidde例如:http://jsfiddle.net/tbbeqcqb/

+0

工作正常。我複製並粘貼了你的容器div,並且我添加了一堆隨機圖像並且它可以工作。你可以做一個問題本身的jsfiddle鏈接? – 2014-08-29 14:18:24

+0

真的,我做了同樣的事情,它工作正常。在這裏檢查http://jsfiddle.net/tbbeqcqb/1/ – Paulquappe 2014-08-29 14:19:02

+0

對不起,我的錯誤。由於某些原因,jsfiddle沒有說明問題。這是它應該是如何:http://www.geoffgoode.com/sample.html但這裏是問題:http://www.geoffgoode.com/sample2.html - 你會注意到圖像已縮小因爲所有圖像的合併寬度正在計算中,而不是每個'.container' – 2014-08-29 14:44:38

回答

0

不是100%肯定你想什麼來實現的,但我認爲這是這一點;

$(window).bind("load", function() { 

    var totalHeight = 100; 
    $('.container').each(function(){ 

    var totalWidth = 1; 
    $(this).children().filter('.imgWrapper').each(function(){ 
     totalWidth += $(this).outerWidth(); 
    }); 

    var containerWidth = $(this).width(); 
    var ratio = totalWidth/totalHeight; 
    var containerHeight = containerWidth/ratio; 

    $(this).css('height',containerHeight + 'px'); 

    var newTotalWidth = 0; 
    $(this).children().filter('.imgWrapper').each(function(){ 
     $(this).children('img').css('height',containerHeight + 'px'); 
     newTotalWidth += $(this).outerWidth(); 
    }); 

    $(this).css('width',newTotalWidth + 'px'); 
    }); 
}); 
相關問題