【问题标题】:Making a function work in all divs with the same class using jquery使用 jquery 使函数在具有相同类的所有 div 中工作
【发布时间】:2014-10-23 13:40:58
【问题描述】:

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

【问题讨论】:

  • 工作正常。我复制并粘贴了您的容器 div,并添加了一堆随机图像,它可以工作。你能做一个问题本身的jsfiddle链接吗?
  • 是的,我也这样做了,而且效果很好。在这里查看jsfiddle.net/tbbeqcqb/1
  • 对不起,我的错误。由于某种原因,jsfiddle 没有说明问题。它应该是这样的:geoffgoode.com/sample.html,但问题是:geoffgoode.com/sample2.html - 你会注意到图像已经缩小,因为正在计算所有图像的组合宽度,而不仅仅是每个 '.container '
  • anwser 有帮助吗?

标签: javascript jquery html css


【解决方案1】:

不是 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');
  });
});

【讨论】:

    猜你喜欢
    • 2014-02-11
    • 2016-10-30
    • 2021-10-09
    • 1970-01-01
    • 2013-05-25
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多