[英]Scale group of images to fit parent width/height
我有一个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
的大小。
如果不能仅使用CSS来完成Javascript / jquery解决方案,那就很好。 谢谢!
编辑:这是(大致) #boxToScale
缩放后,我希望它看起来像什么:
在看到您的图片后,更新了我的答案。
这是基于此jsfiddle.net/7dpHK/2 (你的问题charlietfl评论这一点)。 它几乎可以按您想要的方式工作,但是由于图像周围有4px边框/填充,因此出现了问题。 还有一些令人困惑的CSS。 因此,您必须像这样计算边界:
var border = $("#boxToScale img").length * 4;
然后从parentW
减去它:
parentW = $box.width() - border
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);
});
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边框可能会导致此代码错误。 请参见此处无边界的示例。
#boxToScale {
border: solid blue 1px;
white-space: nowrap;
}
#boxToScale img {
width:20%;
height:auto;
display:inline-block;
}
疯狂..但可能会起作用...希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.