使用 JavaScript 实现网页图片轮播效果 - 完整代码示例
#slideshow {
position: relative;
width: 100%;
height: 400px;
}
#slideshow img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
#slideshow img.active {
opacity: 1;
}
var images = document.querySelectorAll('#slideshow img');
var currentImage = 0;
var slideInterval = setInterval(nextImage, 3000);
function nextImage() {
images[currentImage].classList.remove('active');
currentImage++;
if (currentImage >= images.length) {
currentImage = 0;
}
images[currentImage].classList.add('active');
}
这段代码将在 'slideshow' 元素中显示三张图片,并每三秒钟自动切换到下一张图片。CSS 将所有图片定位到相同的位置并使它们不可见,直到它们被标记为 'active'。JavaScript 将轮流标记每个图像,并将 'active' 类添加到当前图像,使其可见。'setInterval' 函数将每隔三秒钟调用 'nextImage' 函数。
原文地址: https://www.cveoy.top/t/topic/oKH5 著作权归作者所有。请勿转载和采集!