2014-08-29 78 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'); 
    }); 
}); 
相关问题