javascript轮播图
时间: 2023-07-04 10:06:25 浏览: 102
JavaScript轮播图
以下是一个基本的 Javascript 轮播图实现:
HTML 代码:
```html
<div class="slideshow-container">
<div class="slide">
<img src="image1.jpg">
</div>
<div class="slide">
<img src="image2.jpg">
</div>
<div class="slide">
<img src="image3.jpg">
</div>
</div>
<button class="prev">❮</button>
<button class="next">❯</button>
```
CSS 代码:
```css
.slideshow-container {
position: relative;
width: 100%;
height: 400px;
}
.slide {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
font-weight: bold;
padding: 10px;
z-index: 1;
}
.prev {
left: 0;
}
.next {
right: 0;
}
```
Javascript 代码:
```javascript
var slides = document.querySelectorAll('.slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 5000);
function nextSlide() {
slides[currentSlide].style.display = 'none';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].style.display = 'block';
}
function prevSlide() {
slides[currentSlide].style.display = 'none';
currentSlide = (currentSlide - 1 + slides.length) % slides.length;
slides[currentSlide].style.display = 'block';
}
var prev = document.querySelector('.prev');
var next = document.querySelector('.next');
prev.addEventListener('click', prevSlide);
next.addEventListener('click', nextSlide);
```
这个轮播图的实现原理是通过设置每个图片的 `display` 属性来实现轮播效果。初始时,第一张图片显示,其余图片隐藏;然后利用 `setInterval` 函数每隔一段时间自动切换到下一张图片,同时将上一张图片隐藏、下一张图片显示。通过点击“上一页”和“下一页”按钮,可以手动切换图片。
阅读全文