将图像滑块调整为JavaScript中当前图像的纵横比

问题描述 投票:0回答:1

我制作了这个完全可用的图像滑块,现在我唯一要做的就是将其高度调整为当前图像的纵横比。我编写了一个循环,用于计算滑块中每个图像的长宽比,唯一的问题是,执行该循环时,一次返回所有值,而当我只需要它给我一个接一个的adjustedHeight值时点击

[我尝试将i++放入循环中,将所有值推入数组,这需要另一个循环在数组的值之间进行迭代,但是所有这些感觉都比需要的复杂。

<div class="slider-images">
    <img src="https://via.placeholder.com/1280x720.png">
    <img src="https://via.placeholder.com/1280x720.png">
    <img src="https://via.placeholder.com/1280x960.png">
    <img src="https://via.placeholder.com/1280x720.png">
    <img src="https://via.placeholder.com/1280x720.png">
    <img src="https://via.placeholder.com/1280x720.png">
    <img src="https://via.placeholder.com/1280x720.png">
</div>

JavaScript的

const images = document.querySelector('.slider-images');
const image = document.querySelectorAll('.slider-images img');

var i;

function slideRight() {
    //...

    for (i = 0; i < image.length; i++) { // Calculates aspect ratio
        const allImagesWidth = image[i].naturalWidth, 
            allImagesHeight = image[i].naturalHeight;
        const aspectRatio = allImagesWidth / allImagesHeight;
        adjustedHeight = Math.round(slideWidth / aspectRatio); // Final slider height required for a current shown image
    }

    images.style.height = adjustedHeight + 'px'; // Dynamically should add respective height calculated in the loop above

    //...

}
document.querySelector('.slide-right').addEventListener('click', slideRight, false);

CSS

.slider-images {
    display: flex;
    transition: .5s all cubic-bezier(0.4, 0.0, 0.2, 1);
    max-width: 200%;
    max-height: 512px;
}

.slider-images img {
    width: 50%;
    z-index: -1;
}
javascript html slide
1个回答
0
投票
还进行样式调整,将max-height.slider-images中删除,并将.slider-images img设置为max-height: unset;,以防默认情况下将img设置为max-height: 100%;

var position = 0; var index = 0; var imageArray = []; //... for (index; index < image.length; index++) { const allImagesWidth = image[index].naturalWidth, allImagesHeight = image[index].naturalHeight; const aspectRatio = allImagesWidth / allImagesHeight; var adjustedHeight = slideWidth / aspectRatio; imageArray.push(adjustedHeight++); } images.style.height = imageArray[position] + 'px'; function slideRight() { position--; images.style.height = imageArray[position] + 'px'; if (position == -1) { position = imageCount - 1; } images.style.transform = 'translateX(' + -(slideWidth * position) + 'px)'; } // ... document.querySelector('.slide-right').addEventListener('click', slideRight, false);

© www.soinside.com 2019 - 2024. All rights reserved.