以下是一个基本的HTML和CSS实现的图片自动轮播:
HTML:
<div class="slideshow-container">
<div class="slideshow">
<img src="img1.jpg" alt="Image 1" />
<img src="img2.jpg" alt="Image 2" />
<img src="img3.jpg" alt="Image 3" />
</div>
</div>
CSS:
.slideshow-container {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slideshow {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.slideshow img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.slideshow img:nth-of-type(n+2) {
opacity: 0;
}
.slideshow img:first-of-type {
animation: slide 3s infinite;
}
@keyframes slide {
0% {
opacity: 0;
}
5% {
opacity: 1;
}
25% {
opacity: 1;
}
30% {
opacity: 0;
}
100% {
opacity: 0;
}
}
JavaScript:
const slideshow = document.querySelector(".slideshow");
const images = document.querySelectorAll(".slideshow img");
const imgCount = images.length;
let index = 0;
setInterval(() => {
images[index % imgCount].style.opacity = 0;
index++;
images[index % imgCount].style.opacity = 1;
}, 3000);
解释:
- HTML中的div容器设置了宽度、高度和overflow隐藏,使其成为轮播容器;
- CSS中设置了轮播容器的position为相对位置,轮播元素的position为绝对位置,使其悬浮于轮播容器上方;
- CSS中设置了轮播元素的opacity渐变效果,通过nth-of-type选择器实现自动轮播效果;
- JavaScript中,每隔3秒切换一次轮播元素的opacity值实现轮播。
以上代码可以实现基本的轮播,可根据需要进行修改和扩展。