![](/img/trans.png)
[英]jQuery - Trying to make one function to work with multiple, same class, divs
[英]Making a function work in all divs with the same class using jquery
我有一個響應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');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.