javascript - 使用 jquery 使一个函数在具有相同类的所有 div 中工作

标签 javascript jquery html css

我有一个响应式 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/

相关文章:

javascript - 如何使用 FANCYBOX 将多个图库中的图像分组?

javascript - 如何实现html的本地存储?

javascript - 造型 Facebook Likebox

javascript - 检测用户是否在新选项卡中打开链接并重定向到新网址

html - Firefox 在错误的元素上添加边距

javascript - 将 JSON 响应映射到 Vue.js 中的模型类

javascript - 在窗口调整大小和加载时将 div 高度与父级匹配

javascript - 我的点击功能在不应该运行的时候运行

javascript - 将鼠标悬停在一个元素上以将类添加到另一个元素?

javascript - 是否可以仅通过 $.ajax(options) 或 xhr.send(file) 上传文件?