首页 > 解决方案 > 在同一网格上填充不同纵横比的图像

问题描述

这基本上是我正在寻找的,除了 16/9 图像的顶部和底部可能有填充,以便图像水平居中在 div 中:https ://cdn.discordapp.com/attachments/ 846628882538299465/862306008964399114/unknown.png

这就是现在的样子: https ://cdn.discordapp.com/attachments/303475406588215296/862659779390341140/unknown.png

因此,不是所选纵横比的图像只是相互重叠。在我现在的图像中,有 4/3 和 16/9 图像,选择的比例为 4/3。当然,当用户选择 16/9 比例时,4/3 纵横比的图像会得到侧边距。有没有办法让各种纵横比图像适合带有自动填充的网格?

JS

function updateGrid(index) {
    let cells = imageGrid.getElementsByClassName("cell");
    let currentAspectRatio = getAspectRatio();
    let decimalAspectRatio = aspectRatioMap.get(currentAspectRatio)
    let newWidth = ((100 / index).toFixed(2)).toString();
    let newPadding = ((parseInt(newWidth) / decimalAspectRatio).toFixed(2)).toString();
    console.log(currentAspectRatio);
    for(let x = 0; x < cells.length; x++) {
        cells[x].style.width = newWidth + "%";
        cells[x].style.paddingBottom = newPadding + "%";

    }
}
function updateImageGrid(cameras) { 
    imageGrid.innerHTML = "";
    if(cameras === null) return
    for(let e = 0;e < cameras.length; e++) {
        let div = document.createElement("div");
        let divs = document.createElement("div");
        div.innerHTML = "";
        div.classList = "cell";
        divs.id = "grid_" + e;
        let img = document.createElement("img");
        img.id = "camera_" + cameras[e];
        divs.appendChild(img);
        div.appendChild(divs);
        imageGrid.appendChild(div);
    }
}

CSS

  div.cell {
    width: 33.333%;
    padding-bottom: 18.56%;
    
    position: relative;
    float: left;
    transition: 0.2s;
    transition-timing-function: ease-out;
  }
 
  div.cell>div {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
    text-align: center;
  }
 
  div.cell>div img {
    height: 100%;
  }

标签: javascripthtmlcssimagegrid

解决方案


推荐阅读