我有一个响应式 div (.container),其中包含一行嵌套 div (.imgWrapper),每个嵌套 div 包含一个图像 (.imgWrapper img)。以下代码的目的是使所有图像具有相同的高度,同时仍然适合容器中的一行,尽管所有图像彼此之间的比例不同(即横向和纵向)
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/
最佳答案
不是 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');
});
});
关于javascript - 使用 jquery 使一个函数在具有相同类的所有 div 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570049/