簡體   English   中英

縮放圖像組以適合父級寬度/高度

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM