html 最简单的图片轮播
时间: 2023-12-27 12:05:28 浏览: 28
以下是一个使用 HTML、CSS 和 JavaScript 实现的最简单的图片轮播代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>最简单的图片轮播</title>
<style>
.slideshow {
position: relative;
}
.slideshow img {
position: absolute;
left: 0;
top: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slideshow img.active {
opacity: 1;
}
</style>
</head>
<body>
<div class="slideshow">
<img src="image1.jpg" class="active">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<script>
var images = document.querySelectorAll('.slideshow img');
var index = 0;
function nextImage() {
images[index].classList.remove('active');
index++;
if (index >= images.length) {
index = 0;
}
images[index].classList.add('active');
}
setInterval(nextImage, 2000);
</script>
</body>
</html>
```
这段代码中,我们创建了一个名为 `.slideshow` 的 div 容器,容器中包含三张图片,其中第一张图片添加了 `active` 类名,用于表示默认显示的图片。通过 CSS,我们将图片设置为绝对定位,并设置其透明度为 0,通过过渡效果实现了图片的渐变切换。通过 JavaScript,我们使用 `setInterval` 函数定时调用 `nextImage` 函数,实现了轮播效果。`nextImage` 函数通过修改图片的 `active` 类名来实现图片的显示和隐藏。