簡體   English   中英

將圖像 slider 調整為當前圖像在 JavaScript 中的縱橫比

[英]Resize image slider to the current image's aspect ratio in JavaScript

我制作了這個完整的工作圖像 slider,我現在唯一想做的就是將其高度調整為當前圖像的縱橫比。 我寫了一個循環來計算 slider 中每個圖像的縱橫比,唯一的問題是,在執行時,循環一次返回所有值,而我只需要它給我一個又一個的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;
}

終於解決了,按我的意願垂直工作和調整大小。 只需將循環移動到slideRight function 上方,設置新的空數組變量imageArray ,將循環中的所有內容push送到該數組,然后在 function 中設置樣式以從該數組讀取並根據已存在的變量position = 0讀取並更改寬度position = 0用於 slider 工作。

在 styles 中也進行了調整,從.slider-images中移除了max-height ,並將.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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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