🎠 轮播图切换

使用 translateX 实现流畅的图片轮播效果,支持手动控制和自动播放

使用的知识点: translateX() 📈 transition-timing-function 🔗 多重变换

交互演示

使用左右箭头按钮或点击指示器切换幻灯片,也可以开启自动播放:

💡 提示:点击左右箭头切换幻灯片,点击底部圆点跳转到指定幻灯片

实现步骤

步骤 1:HTML 结构

创建轮播图的基本结构,包括视口、轨道和幻灯片:

HTML
<!-- 轮播图容器 -->
<div class="carousel-container">
  <!-- 视口 - 只显示一张幻灯片 -->
  <div class="carousel-viewport">
    <!-- 轨道 - 包含所有幻灯片 -->
    <div class="carousel-track">
      <div class="carousel-slide">幻灯片 1</div>
      <div class="carousel-slide">幻灯片 2</div>
      <div class="carousel-slide">幻灯片 3</div>
    </div>
  </div>

  <!-- 导航按钮 -->
  <button class="prev-btn"></button>
  <button class="next-btn"></button>

  <!-- 指示器 -->
  <div class="carousel-indicators">
    <button data-index="0"></button>
    <button data-index="1"></button>
    <button data-index="2"></button>
  </div>
</div>

步骤 2:CSS 样式

使用 flexbox 和 translateX 实现轮播效果:

CSS
/* 视口 - 隐藏溢出内容 */
.carousel-viewport {
  overflow: hidden;
  width: 100%;
}

/* 轨道 - 使用 flexbox 横向排列 */
.carousel-track {
  display: flex;
  transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 幻灯片 - 每张占满视口宽度 */
.carousel-slide {
  min-width: 100%;
  height: 100%;
}

步骤 3:JavaScript 切换逻辑

使用 translateX 移动轨道来切换幻灯片:

JavaScript
let currentIndex = 0;
const track = document.querySelector('.carousel-track');
const slides = document.querySelectorAll('.carousel-slide');
const totalSlides = slides.length;

// 更新轮播图位置
function updateCarousel() {
  const offset = -currentIndex * 100;
  track.style.transform = `translateX(${offset}%)`;
}

// 下一张
function nextSlide() {
  currentIndex = (currentIndex + 1) % totalSlides;
  updateCarousel();
}

// 上一张
function prevSlide() {
  currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
  updateCarousel();
}

步骤 4:添加指示器

实现点击指示器跳转到指定幻灯片:

JavaScript
const indicators = document.querySelectorAll('.carousel-indicator');

// 更新指示器状态
function updateIndicators() {
  indicators.forEach((indicator, index) => {
    indicator.classList.toggle('active', index === currentIndex);
  });
}

// 点击指示器跳转
indicators.forEach(indicator => {
  indicator.addEventListener('click', () => {
    currentIndex = parseInt(indicator.dataset.index);
    updateCarousel();
    updateIndicators();
  });
});

步骤 5:自动播放功能

实现可选的自动播放功能:

JavaScript
let autoplayInterval = null;

// 开启自动播放
function startAutoplay() {
  autoplayInterval = setInterval(() => {
    nextSlide();
  }, 3000); // 每 3 秒切换
}

// 停止自动播放
function stopAutoplay() {
  if (autoplayInterval) {
    clearInterval(autoplayInterval);
    autoplayInterval = null;
  }
}

关键要点

← 返回实战应用列表