这里有一个简单的JS轮播示例:

HTML

<div class="slider">
  <img src="image1.jpg" alt="Image 1">
  <img src="image2.jpg" alt="Image 2">
  <img src="image3.jpg" alt="Image 3">
  <img src="image4.jpg" alt="Image 4">
</div>

CSS

.slider {
  position: relative;
  width: 600px;
  height: 400px;
  overflow: hidden;
}

.slider img {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.slider img.active {
  opacity: 1;
}

JS

const slider = document.querySelector('.slider');
const images = slider.querySelectorAll('img');
let currentIndex = 0;

function showImage(index) {
  images[currentIndex].classList.remove('active');
  images[index].classList.add('active');
  currentIndex = index;
}

setInterval(() => {
  let nextIndex = currentIndex + 1;
  if (nextIndex >= images.length) {
    nextIndex = 0;
  }
  showImage(nextIndex);
}, 5000);

解释:

  • 首先,我们选中包含图片的<div>元素和所有<img>元素。
  • 然后,我们定义一个变量currentIndex来跟踪当前显示的图片的索引。
  • 我们编写一个showImage()函数,该函数将从当前图像切换到给定索引的图像。它会增加一个名为“active”的CSS类,该类将使图像变为可见。
  • 最后,我们使用setInterval()函数来以5秒的间隔循环显示下一个图像。在循环中,我们计算下一个要显示的图像的索引,然后调用showImage()函数。如果达到图像数组的末尾,则将索引重置为0。
写一个js轮播

原文地址: https://www.cveoy.top/t/topic/bJMx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录