JS之旋轉(zhuǎn)輪播圖代碼怎么寫(xiě)

js
小億
95
2024-05-06 20:12:54

以下是一個(gè)簡(jiǎn)單的JavaScript代碼示例,用于創(chuàng)建一個(gè)基本的旋轉(zhuǎn)輪播圖:

<!DOCTYPE html>
<html>
<head>
  <title>Simple Carousel</title>
  <style>
    .carousel {
      display: flex;
      overflow: hidden;
      width: 300px;
      height: 200px;
    }
    .slide {
      flex: 0 0 auto;
      width: 300px;
      height: 200px;
      transition: transform 0.5s;
    }
  </style>
</head>
<body>

<div class="carousel">
  <div class="slide" style="background-color: #ff5733;">Slide 1</div>
  <div class="slide" style="background-color: #33ff57;">Slide 2</div>
  <div class="slide" style="background-color: #5733ff;">Slide 3</div>
</div>

<script>
  const carousel = document.querySelector(".carousel");
  const slides = document.querySelectorAll(".slide");
  let currentIndex = 0;

  function showSlide(index) {
    const offset = -index * 300;
    carousel.style.transform = `translateX(${offset}px)`;
  }

  function showNextSlide() {
    currentIndex = (currentIndex + 1) % slides.length;
    showSlide(currentIndex);
  }

  setInterval(showNextSlide, 2000);
</script>

</body>
</html>

在這個(gè)示例中,我們創(chuàng)建了一個(gè)包含3個(gè)幻燈片的旋轉(zhuǎn)輪播圖。我們使用setInterval()函數(shù)來(lái)定時(shí)切換幻燈片,每隔2秒切換一次。在showSlide()函數(shù)中,我們使用transform屬性來(lái)平移輪播圖,從而實(shí)現(xiàn)幻燈片之間的切換效果。

您可以根據(jù)需要自定義輪播圖的樣式和功能。希望這個(gè)示例能幫助到您!

0