帮我写一个轮播图网页的代码
时间: 2023-05-22 13:06:21 浏览: 103
图片轮播代码
当然,很乐意帮您写一个轮播图网页的代码。以下是代码示例:
HTML代码:
```
<div class="slideshow-container">
<div class="slide">
<img src="image1.jpg">
<div class="caption">Caption 1</div>
</div>
<div class="slide">
<img src="image2.jpg">
<div class="caption">Caption 2</div>
</div>
<div class="slide">
<img src="image3.jpg">
<div class="caption">Caption 3</div>
</div>
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
```
CSS代码:
```
.slideshow-container {
position: relative;
width: 100%;
}
.slide {
display: none;
position: absolute;
top: 0;
left: 0;
}
.slide img {
width: 100%;
height: auto;
}
.slide .caption {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background: rgba(0, 0, 0, 0.8);
color: #fff;
padding: 10px 0;
text-align: center;
font-size: 18px;
}
.prev, .next {
position: absolute;
top: 50%;
display: none;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
.prev:hover, .next:hover {
color: #fff;
}
.slide.active {
display: block;
}
.show-caption {
animation: show-caption 0.5s ease forwards;
}
.hide-caption {
animation: hide-caption 0.5s ease forwards;
}
@keyframes show-caption {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
@keyframes hide-caption {
from {
transform: translateY(0);
}
to {
transform: translateY(100%);
}
}
```
JavaScript代码:
```
const slides = document.querySelectorAll('.slide');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentIndex = 0;
function showSlide(index) {
slides[currentIndex].classList.remove('active', 'show-caption');
slides[currentIndex].classList.add('hide-caption');
currentIndex = index;
slides[currentIndex].classList.add('active', 'show-caption');
slides[currentIndex].classList.remove('hide-caption');
}
prevBtn.addEventListener('click', () => {
showSlide(currentIndex === 0 ? slides.length - 1 : currentIndex - 1);
});
nextBtn.addEventListener('click', () => {
showSlide(currentIndex === slides.length - 1 ? 0 : currentIndex + 1);
});
showSlide(0);
setInterval(() => {
showSlide(currentIndex === slides.length - 1 ? 0 : currentIndex + 1);
}, 5000);
```
这段代码会创建一个包含轮播图的容器(`.slideshow-container`)和轮播图的各个幻灯片(`.slide`)。轮播图的前进和后退按钮(`.prev`和`.next`)将启用用户操作。我们还为幻灯片添加了一个标题(`.caption`),例如“Caption 1”,以及一些JavaScript代码,用于在幻灯片之间自动切换。
阅读全文