包含图像的容器,其数量可以变化
<div class="container">
<img src="https://unsplash.it/500/400">
<img src="https://unsplash.it/400/500">
<img src="https://unsplash.it/500/500">
</div>
这些图像的高度不同。我要调整它们的大小,以使它们都具有相同的高度,并且它们是可以提供的最大宽度。
我觉得答案涉及弹性框和object-fit:
,但我不能完全拼凑起来。
答案 0 :(得分:0)
类似的事情会起作用,我添加了注释来解释逻辑。
// Find all img elements in .container.
const images = Array.prototype.slice.call(document.querySelectorAll('.container img'));
// Add load event listener
images.forEach(image => image.addEventListener('load', imageLoad));
// Define initial minimum height
let minHeight = Infinity;
let imagesLoaded = 0;
// Image load event handler
function imageLoad(event) {
// Recalculate minimum image height
minHeight = Math.min(minHeight, event.target.height);
imagesLoaded++;
// Apply minimum height once all images are loaded
if (images.length === imagesLoaded) {
images.forEach(image => image.style.height = `${minHeight}px`);
}
}
<div class="container">
<img src="https://unsplash.it/400/500">
<img src="https://unsplash.it/500/300">
<img src="https://unsplash.it/500/500">
</div>