简体   繁体   English

当图像大小不同时,如何在 carasoul 中制作响应式图像?

[英]How to make responsive image in carasoul while the images are in different sizes?

I'm having some trouble with the images in one of my pages.我的一个页面中的图像有一些问题。 They are in a carousel, but as the carousel slides to the next image, it is constantly changing sizes because the images are different sizes.它们在轮播中,但随着轮播滑动到下一张图像,它会不断改变大小,因为图像的大小不同。 I have tried to set them all to be the same size, but it doesn't seem to matter, they are still different sizes.我试图将它们全部设置为相同的大小,但这似乎并不重要,它们仍然是不同的大小。 What do I need to do to make it so they are the same size so the carousel will remain consistent through each slide?我需要做什么才能使它们具有相同的大小,以便轮播在每张幻灯片中保持一致?

Using aspect-ratio使用aspect-ratio

So, you can ignore the JavaScript and HTML in the snippet below.因此,您可以忽略下面代码段中的 JavaScript 和 HTML。

In CSS what I've done is given a fixed width of 150px to all my images and a 1:1 aspect-ratio (because I know all my images are square).150px中,我所做的是为我的所有图像提供 150 像素的固定width1:1 aspect-ratio (因为我知道我的所有图像都是方形的)。

Comment out the aspect-ratio code and you can see the difference.注释掉aspect-ratio代码,您可以看到差异。

 let currImg = 0, totalImgs = 4; const container = document.getElementById("container"), leftBtn = document.getElementById("left-btn"), rightBtn = document.getElementById("right-btn"), nav = (delta) => { container.children[currImg].classList.remove("show") currImg = (currImg + totalImgs + delta) % totalImgs container.children[currImg].classList.add("show") }, navLeft = () => nav(-1), navRight = () => nav(1) leftBtn.addEventListener("click", navLeft) rightBtn.addEventListener("click", navRight)
 img { width: 150px; aspect-ratio: 1/1; display: none; margin-bottom: 0.5rem; }.show { display: block; }
 <div id="container"> <img src="https://placekitten.com/200/200" class="show" /> <img src="https://placekitten.com/300/300" /> <img src="https://placekitten.com/500/500" /> <img src="https://placekitten.com/600/600" /> </div> <button id="left-btn">Left</button> <button id="right-btn">Right</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM