返回

利用原生 JS 实现轮播图,进阶之道

前端

在 Web 开发中,轮播图是展示动态图像的常用元素。利用原生 JS 实现轮播图不仅能提升您的编程技能,还能深化您对浏览器对象模型 (BOM) 和文档对象模型 (DOM) 的理解。本文将逐步引导您构建一个原生 JS 轮播图,让您亲身体验其背后的原理。

拆分复杂功能

轮播图的实现涉及多个功能模块:

  • 图片切换: 流畅地从一张图片过渡到另一张。
  • 指示器: 显示当前显示的图片的索引。
  • 箭头导航: 使用箭头按钮手动控制轮播。
  • 自动播放: 设置轮播图在一定时间间隔后自动切换。

利用 BOM 和 DOM

BOM (浏览器对象模型)提供浏览器环境的接口,而 DOM (文档对象模型)表示 HTML 文档的结构。在我们的轮播图中,我们将使用以下 BOM 和 DOM 方法:

  • document.querySelector() :获取 DOM 中的元素。
  • Element.classList.add()Element.classList.remove() :操纵元素的 CSS 类。
  • setInterval() :设置一个定时器,定期执行代码。

构建图片切换模块

首先,定义一个函数来切换图片:

function switchImage(index) {
  // 获取所有图片
  const images = document.querySelectorAll(".image");

  // 隐藏所有图片
  images.forEach((image) => image.classList.remove("active"));

  // 显示当前图片
  images[index].classList.add("active");
}

添加指示器模块

接下来,添加一个指示器来显示当前图片索引:

<ul class="indicators">
  <li class="indicator active"></li>
  <li class="indicator"></li>
  <li class="indicator"></li>
</ul>
function updateIndicators(index) {
  // 获取所有指示器
  const indicators = document.querySelectorAll(".indicator");

  // 移除所有指示器的活动状态
  indicators.forEach((indicator) => indicator.classList.remove("active"));

  // 为当前指示器添加活动状态
  indicators[index].classList.add("active");
}

实现箭头导航模块

为了提供手动控制,添加箭头导航:

<button class="arrow prev">&lt;</button>
<button class="arrow next">&gt;</button>
const prevButton = document.querySelector(".prev");
const nextButton = document.querySelector(".next");

prevButton.addEventListener("click", () => switchImage(currentIndex - 1));
nextButton.addEventListener("click", () => switchImage(currentIndex + 1));

添加自动播放模块

最后,添加自动播放功能:

let interval;

function startAutoplay() {
  interval = setInterval(() => {
    switchImage(currentIndex + 1);
  }, 3000);
}

完整代码

<!DOCTYPE html>
<html>
<head>
  <style>
    .carousel {
      position: relative;
      width: 500px;
      height: 300px;
      overflow: hidden;
    }

    .image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: opacity 0.5s ease-in-out;
    }

    .image.active {
      opacity: 1;
    }

    .indicators {
      position: absolute;
      bottom: 10px;
      left: 50%;
      transform: translate(-50%, 0);
    }

    .indicator {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin: 0 5px;
      background-color: #ccc;
      border-radius: 50%;
    }

    .indicator.active {
      background-color: #000;
    }

    .arrows {
      position: absolute;
      top: 50%;
      left: 10px;
      transform: translateY(-50%);
    }

    .arrow {
      border: none;
      background-color: transparent;
      font-size: 24px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div class="carousel">
    <img class="image active" src="image1.jpg" alt="Image 1">
    <img class="image" src="image2.jpg" alt="Image 2">
    <img class="image" src="image3.jpg" alt="Image 3">
  </div>

  <ul class="indicators">
    <li class="indicator active"></li>
    <li class="indicator"></li>
    <li class="indicator"></li>
  </ul>

  <div class="arrows">
    <button class="arrow prev">&lt;</button>
    <button class="arrow next">&gt;</button>
  </div>

  <script>
    // 图片切换函数
    function switchImage(index) {
      const images = document.querySelectorAll(".image");

      images.forEach((image) => image.classList.remove("active"));

      images[index].classList.add("active");
    }

    // 更新指示器函数
    function updateIndicators(index) {
      const indicators = document.querySelectorAll(".indicator");

      indicators.forEach((indicator) => indicator.classList.remove("active"));

      indicators[index].classList.add("active");
    }

    // 箭头导航事件监听器
    const prevButton = document.querySelector(".prev");
    const nextButton = document.querySelector(".next");

    prevButton.addEventListener("click", () => switchImage(currentIndex - 1));
    nextButton.addEventListener("click", () => switchImage(currentIndex + 1));

    // 自动播放函数
    let interval;

    function startAutoplay() {
      interval = setInterval(() => {
        switchImage(currentIndex + 1);
      }, 3000);
    }

    // 初始化
    let currentIndex = 0;
    startAutoplay();
  </script>
</body>
</html>

总结

通过分解轮播图的复杂性,我们分步构建了一个原生 JS 轮播图。我们探讨了 BOM 和 DOM 的重要性,并学习了如何使用 JS 操纵 HTML 元素。

这不仅加强了您的 JS 技能,还加深了您对 Web 开发原理的理解。通过动手实践,您已经成为原生 JS 轮播图的大师。