0

5枚の画像があり、1枚目から5枚目まで自動でスライドするのですが、5枚目でストップしてしまいます。
1枚目に戻り再度、自動でスライドさせ、その工程を無限に繰り返したいのですが、出来ず教えていただきたいです。

現在のコード:

const next = document.getElementById('next');
const prev = document.getElementById('prev');
const ul = document.querySelector('.hero ul');
const slides = ul.children;
const dots = [];
let currentIndex = 0;

function updateButtons() {
    prev.classList.remove('hidden');
    next.classList.remove('hidden');
    if (currentIndex === 0) {
        prev.classList.add('hidden');
    }
    if (currentIndex === slides.length - 1) {
        next.classList.add('hidden');
    }
}

function moveSlides() {
    const slideWidth = slides[0].getBoundingClientRect().width;
    ul.style.transform = `translateX(${-1 * slideWidth * currentIndex}px)`;
}

function setupDots() {
    for (let i = 0; i < slides.length; i += 1) {
        const button = document.createElement('button');
        button.addEventListener('click', () => {
            currentIndex = i;
            // dots.forEach(dot => {
            //   dot.classList.remove('current');
            // });
            // dots[currentIndex].classList.add('current');
            updateDots();
            updateButtons();
            moveSlides();
        });
        dots.push(button);
        document.querySelector('.carousel nav').appendChild(button);
    }

    dots[0].classList.add('current');
}

function updateDots() {
    dots.forEach(dot => {
        dot.classList.remove('current');
    });
    dots[currentIndex].classList.add('current');

}
updateButtons();
setupDots();

function showTime() {
    currentIndex++;
    updateButtons();
    updateDots();
    moveSlides();
    if (currentIndex > slides.length) {
        currentIndex++;
    } else if (currentIndex === 5) {
        currentIndex = 0;
        updateButtons();
        updateDots();
        moveSlides();
    }
}
// const intervalId = setInterval(showTime, 1000);
setInterval(showTime, 1000);

next.addEventListener('click', () => {
    currentIndex += 1;
    updateButtons();
    // const slideWidth = slides[0].getBoundingClientRect().width;
    // ul.style.transform = `translateX(${-1 * slideWidth * currentIndex}px)`;
    updateDots();
    moveSlides();
});

prev.addEventListener('click', () => {
    currentIndex -= 1;
    updateButtons();
    // const slideWidth = slides[0].getBoundingClientRect().width;
    // ul.style.transform = `translateX(${-1 * slideWidth * currentIndex}px)`;
    updateDots();
    moveSlides();
});

window.addEventListener('resize', () => {
    moveSlides();
});

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。