简体   繁体   中英

Making a function work in all divs with the same class using jquery

I have a responsive div (.container) that contains a row of nested divs (.imgWrapper) that each contain an image (.imgWrapper img). The purpose of the following code is to make all images the same height while still fitting in one row in the container despite all images being a different proportion to one another (ie landscape and portrait)

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");

});

});

This all works great if there is only one div with the class '.container', however as soon as I add div with the same class, the function is applied to all images instead of images in each '.container' div. How to I apply this function to each '.container' div one at a time?

Here is a jsfidde example: http://jsfiddle.net/tbbeqcqb/

Not 100% sure what you are trying to achieve, but I think it's this;

$(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');
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM