Javascript 缩放图像组以适应父级宽度/高度

Javascript 缩放图像组以适应父级宽度/高度,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个div,里面有各种大小的图像,它位于父容器中 <div id="parentContainer"> <div id="boxToScale"> <img src="http://placehold.it/350x150" /> <img src="http://placehold.it/150x350" /> <img src="http://placehold.it/200x200" /> &l

我有一个div,里面有各种大小的图像,它位于父容器中

<div id="parentContainer">
<div id="boxToScale">
    <img src="http://placehold.it/350x150" />
    <img src="http://placehold.it/150x350" />
    <img src="http://placehold.it/200x200" />
    <img src="http://placehold.it/50x200" />
</div>
</div>

我需要缩放
#boxToScale
,使其适合
#parentContainer
(宽度和高度)内部的所有图像保持其纵横比。所有图像应以相同的因子缩放,并保持在同一条线上

下面是一个JSFIDLE,显示了设置:

我发现了很多可以按比例缩放单个图像的东西,但不能按比例缩放一组图像。我事先不知道图像的大小,只有
#parentContainer
的大小

如果不能只用css实现Javascript/jquery解决方案,那么它就可以了。谢谢

编辑:以下是(大致)缩放
#boxToScale
后我希望它的外观:


疯狂。。但可能有用。。。希望有帮助。

在我看到你的照片后更新了我的答案,你的照片会是什么样子

这是基于此(charlietfl对您的问题发表了评论)。它几乎可以像你想要的那样工作,但是由于图像周围有4倍的边框/填充物,它被窃听了。还有一些令人困惑的CSS。 因此,您必须计算边界,如:

var border = $("#boxToScale img").length * 4;
然后从
parentW
中减去:

parentW = $box.width() - border

JS:

JS:


注意:图像中的1px边框可能会对该代码产生错误。请看一个无国界的例子。

可能有效。
几乎不是答案。。。。在这种情况下,它肯定不会。应该用演示来证明你的解决方案这就是你想要的吗?不确定其他布局参数,如将顶部设置为图像垂直居中。@charlietfl“所有图像应以相同的因子缩放,并保持在同一行上。”但这并不能做到这一点。所有图像应按高度和宽度调整大小。需要更明确的缩放定义。在FF中,他们对我的看法是一致的,并不完全清楚你的期望是什么。没有人能比别人高?就我所见,纵横比目前一直保持不变。显示所需内容的好方法是手动设置图像尺寸/位置,以显示预期输出或提供布局图像expected@charlietfl我添加了一张显示我想要的图片。你是对的,我应该在我对预期布局的定义中更加明确。仅供参考-如果需要,元素总数可以使用
$('selector')。长度
,无需创建
每个
循环实际上:看起来()图像的缩放比例不相同。在该链接中,第一个图像的缩放比例是第二个图像的两倍。我希望它们都以相同的比例缩放。(因此,2000x2000图像在缩放后仍将是1000x1000图像的两倍大。)@penguinrob Yea,我第一次错误地理解了你的问题。请参阅更新的答案。
parentW = $box.width() - border
var border = $("#boxToScale img").length * 4; // 4px padding around every image
var $box = $('#boxToScale'),
    parentW = $box.width() - border,
    parentH = $box.height(),
    imageTotalW = 0,
    imageTotalH = 0,
    $imgs = $box.children();

$imgs.each(function () {
    var img = $(this),
        ht = img.height(),
        w = img.outerWidth()

    imageTotalW += w;
    img.data('w', w);

});

var img_width_ratio = parentW / imageTotalW;
$imgs.each(function (idx) {
    var $this = $(this),
        $prev = $this.prev();
    $this.width($this.outerWidth() * img_width_ratio);
});
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
    var ratio = [maxWidth / srcWidth, maxHeight / srcHeight ];
    ratio = Math.min(ratio[0], ratio[1]);

    return { width:srcWidth*ratio, height:srcHeight*ratio };
}

imagesInContainer = $("#boxToScale img").length;

var toWidth = $("#parentContainer").width() / imagesInContainer;
var toHeight = $("#parentContainer").height() / imagesInContainer;

$("#boxToScale img").each(function(){
    var imageWidth = $(this).width();
    var imageHeight = $(this).height();
    var getRatio = calculateAspectRatioFit(imageWidth, imageHeight, toWidth, toHeight);
    $(this).width(getRatio.width);
    $(this).height(getRatio.height);
});