css 我如何创建一个carousel,幻灯片上的下一个和上一个按钮点击,这carousel应该切换div而不是图像

mctunoxg  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(128)

我想要一个幻灯片效果,切换之间的div上一个按钮,下一个和上一个点击

<div class="container">
    <div class="carousel">
        <div>slide 1</div>
        <div>slide 2</div>
        <div>slide 3</div>
        <div>slide 4</div>
    </div>
    <button>1</button>
    <button>2</button>
</div>

删除了我试过的大部分代码。

<div class="container">
    <div class="carousel">
        <div>slide 1</div>
        <div>slide 2</div>
        <div>slide 3</div>
        <div>slide 4</div>
    </div>
    <button>1</button>
    <button>2</button>
</div>
xriantvc

xriantvc1#

不管你有图片还是div,机制都是一样的。你基本上设置了初始活动幻灯片,创建了转到上一张或下一张幻灯片的函数。每次你都需要检查活动幻灯片是第一张还是最后一张。

const slides = document.querySelectorAll(".carousel div")
const firstSlide = 0
const lastSlide = slides.length - 1
let activeSlide = 0

const goToPreviousSlide = () => {
  slides[activeSlide].classList.remove("active")
  if (activeSlide !== firstSlide) {
    activeSlide = activeSlide - 1
  } else {
    activeSlide = lastSlide
  }
  slides[activeSlide].classList.add("active")
}

const goToNextSlide = () => {
  slides[activeSlide].classList.remove("active")
  if (activeSlide !== lastSlide) {
    activeSlide = activeSlide + 1
  } else {
    activeSlide = firstSlide
  }
  slides[activeSlide].classList.add("active")
}
.container {
  display: flex;
}
.carousel {
  padding: 2rem;
}
.carousel div {
  display: none;
}
.carousel div.active {
  display: block;
}
<div class="container">
    <button onclick="goToPreviousSlide()">Previous</button>
    <div class="carousel">
        <div class="active">slide 1</div>
        <div>slide 2</div>
        <div>slide 3</div>
        <div>slide 4</div>
    </div>
    <button onclick="goToNextSlide()">Next</button>
</div>

相关问题