.carousel {
  position: relative;
  width: 500px;
  height: 300px;
  overflow: hidden;
}

.carousel img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.carousel img.active {
  opacity: 1;
}
var currentIndex = 0;
var images = document.getElementById('carousel').getElementsByTagName('img');

function changeImage() {
  // 将当前图片的透明度设为0,隐藏图片
  images[currentIndex].classList.remove('active');

  // 计算下一个要显示的图片的索引
  currentIndex = (currentIndex + 1) % images.length;

  // 将下一个图片的透明度设为1,显示图片
  images[currentIndex].classList.add('active');
}

该示例使用一个 div 元素作为轮播图容器,并使用 img 元素来展示图片。CSS 样式控制了图片的显示和隐藏,并添加了过渡效果。JavaScript 代码通过 currentIndex 变量记录当前图片索引,并使用 changeImage 函数实现图片切换效果。HTML 中使用一个按钮触发 changeImage 函数。

前端轮播图图片更新示例 - JavaScript 代码实现

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

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