单击左侧滑块时,查看框消失

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

我对 JavaScript 很陌生。

我的审阅滑块适用于右侧的按钮,但是当单击左侧并尝试从第一张幻灯片到左侧最后一张幻灯片时,审阅框会消失

const slides = document.querySelectorAll('.slide')
const leftBtn = document.getElementById('left')
const rightBtn = document.getElementById('right')

let activeSlide = 0

rightBtn.addEventListener('click', () => {
  activeSlide++

  if (activeSlide > slides.length - 1) {
    activeSlide = 0
  }

  setActiveSlide()
})

leftBtn.addEventListener('click', () => {
  activeSlide--

  if (activeSlide > slides.length - 1) {
    activeSlide = slides.length - 1
  }

  setActiveSlide()
})

function setActiveSlide() {
  slides.forEach(slide => {
    slide.classList.remove('active')
    slide.classList.add('hide')
  })

  slides [activeSlide].classList.add('active')
  slides [activeSlide].classList.remove('hide')
}
<section class="section-recensies">
    <div class="recensies container">
        <h2>Recensies</h2>
        <div class="slider-container">

            <div class="recensie-box slide active">
                <p class="recensie-tekst">Recensie</p>
                <img src="{{ asset('images/logo/grace-business-group-lijn-met-kroon.png') }}"
                     alt="Logo Grace Business Group met lijn">
                <p>
                    <span>Naam</span>
                    <span>Bedrijf</span>
                </p>
            </div>

            <div class="recensie-box slide hide">
                <p class="recensie-tekst">Recensie</p>
                <img src="{{ asset('images/logo/grace-business-group-lijn-met-kroon.png') }}"
                     alt="Logo Grace Business Group met lijn">
                <p>
                    <span>Naam</span>
                    <span>Bedrijf</span>
                </p>
            </div>

            <div class="recensie-box slide hide">
                <p class="recensie-tekst">Recensie</p>
                <img src="{{ asset('images/logo/grace-business-group-lijn-met-kroon.png') }}"
                     alt="Logo Grace Business Group met lijn">
                <p>
                    <span>Naam</span>
                    <span>Bedrijf</span>
                </p>
            </div>

            <button class="recensie-button recensie-button-links" id="left"><</button>
            <button class="recensie-button recensie-button-rechts" id="right">></button>

        </div>
    </div>
</section>

我不明白为什么它不起作用,因为它确实向左移动。当我单击右键时,审阅框再次出现。

javascript html
1个回答
0
投票

单击右侧按钮时,此逻辑会检查您是否已导航到最后一张幻灯片并重置到第一张幻灯片:

if (activeSlide > slides.length - 1) {
  activeSlide = 0
}

当单击左侧按钮时,此逻辑会检查 是否已浏览到最后一张幻灯片并重置到最后一张幻灯片:

if (activeSlide > slides.length - 1) {
  activeSlide = slides.length - 1
}

向左导航永远不会超过最右边的幻灯片。 或者,用数学术语来说,如果

activeSlide
当前小于最高值,则递减它永远不会使其大于最高值。

您想检查它是否小于最小值:

if (activeSlide < 0) {
  activeSlide = slides.length - 1
}
© www.soinside.com 2019 - 2024. All rights reserved.