要实现带箭头左右切换的 JavaScript 代码,你可以使用 HTML、CSS 和 JavaScript 来创建一个简单的轮播(carousel)效果。以下是一个基本的示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .carousel-container {
      position: relative;
      width: 100%;
      overflow: hidden;
    }

    .carousel {
      display: flex;
      transition: transform 0.5s ease-in-out;
    }

    .carousel-item {
      min-width: 100%;
    }

    .arrow {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
      font-size: 24px;
    }

    .arrow-left {
      left: 10px;
    }

    .arrow-right {
      right: 10px;
    }
  </style>
</head>
<body>

<div class="carousel-container">
  <div class="carousel">
    <div class="carousel-item">1</div>
    <div class="carousel-item">2</div>
    <div class="carousel-item">3</div>
    <!-- Add more items as needed -->
  </div>

  <div class="arrow arrow-left" onclick="prevSlide()">&#9665;</div>
  <div class="arrow arrow-right" onclick="nextSlide()">&#9655;</div>
</div>

<script>
  let currentIndex = 0;
  const totalItems = document.querySelectorAll('.carousel-item').length;

  function showSlide(index) {
    const carousel = document.querySelector('.carousel');
    const itemWidth = document.querySelector('.carousel-item').clientWidth;
    const newPosition = -index * itemWidth;
    carousel.style.transform = `translateX(${newPosition}px)`;
    currentIndex = index;
  }

  function nextSlide() {
    currentIndex = (currentIndex + 1) % totalItems;
    showSlide(currentIndex);
  }

  function prevSlide() {
    currentIndex = (currentIndex - 1 + totalItems) % totalItems;
    showSlide(currentIndex);
  }
</script>

</body>
</html>

这个示例包含一个带有箭头切换的简单轮播,你可以根据需要进行修改。添加更多的 .carousel-item 元素,以增加轮播中的项目数量。 CSS 中的样式可以根据你的设计进行调整。

版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/javascript.html
本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!