在 JavaScript 中实现图片幻灯片效果有多种方法,以下是一种基本的实现方法:
HTML 结构:
CSS 样式:
#slideshow { position: relative; width: 500px; height: 300px; overflow: hidden; } #slideshow img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; transition: opacity 1s ease; } #slideshow img.active { opacity: 1; }
JavaScript 代码:
var images = document.querySelectorAll('#slideshow img'); var currentImageIndex = 0; function showImage(index) { // 隐藏所有图片 for (var i = 0; i < images.length; i++) { images[i].classList.remove('active'); } // 显示指定索引的图片 images[index].classList.add('active'); } function nextImage() { currentImageIndex++; if (currentImageIndex >= images.length) { currentImageIndex = 0; } showImage(currentImageIndex); } // 设置定时器,每隔3秒切换到下一张图片 setInterval(nextImage, 3000); // 初始化显示第一张图片 showImage(currentImageIndex);
以上代码中,使用了 CSS 的 opacity
属性和过渡效果来实现图片的渐变显示和隐藏。JavaScript 部分使用定时器来定时切换图片,并通过添加和移除 active
类来控制图片的显示和隐藏。