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

时间:2013-10-27 00:22:37

标签: javascript jquery html css css3

我有一个包含各种大小图像的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(宽度和高度),而其中的所有图像都保持其宽高比。所有图像都应按相同因子缩放,并保持在同一行。

这是一个显示设置的jsfiddle:http://jsfiddle.net/32sm4/

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

Javascript / jquery解决方案很好,如果不能用css完成。谢谢!

编辑:这是(大致)在缩放#boxToScale之后我想要的样子: enter image description here

2 个答案:

答案 0 :(得分:1)

在看到你的照片之后,我的答案更新了你的照片。

这是基于此jsfiddle.net/7dpHK/2 charlietfl 在您的问题上对此进行了评论)。它几乎像你想要的那样工作,但它是因为图像周围的4px边框/填充而烦恼。还有一些令人困惑的CSS。 所以你必须计算你的边界,如:

var border = $("#boxToScale img").length * 4;

然后从parentW

中减去它
parentW = $box.width() - border

<强> Working example.

JS:

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

DEMO

JS:

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

注意:图片中的1px边框可能会错误此代码。请参阅示例here无国界。

答案 1 :(得分:-1)

#boxToScale {
border: solid blue 1px;
white-space: nowrap;
}

#boxToScale img {
 width:20%;
 height:auto;
 display:inline-block;
 }
疯狂..但可能有用...希望它有所帮助。