用JavaScript写个轮播图
时间: 2023-06-02 10:05:36 浏览: 77
好的,我可以为您提供JavaScript编写轮播图的相关资料。以下是一个简单的实现示例:
HTML 代码:
```html
<div class="slider-container">
<div class="slider-item active">
<img src="image-1.jpg">
</div>
<div class="slider-item">
<img src="image-2.jpg">
</div>
<div class="slider-item">
<img src="image-3.jpg">
</div>
<div class="slider-item">
<img src="image-4.jpg">
</div>
</div>
```
CSS 代码:
```css
.slider-container {
position: relative;
overflow: hidden;
}
.slider-item {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slider-item.active {
opacity: 1;
}
```
JavaScript 代码:
```javascript
var slideIndex = 0;
var timer;
function showSlides() {
var slides = document.getElementsByClassName('slider-item');
for (var i = 0; i < slides.length; i++) {
slides[i].classList.remove('active');
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides[slideIndex - 1].classList.add('active');
timer = setTimeout(showSlides, 3000); // 切换间隔时间为3秒
}
showSlides();
```
这段代码实现了一个简单的自动轮播图,每张图片切换的间隔时间为3秒,您可以根据需要进行修改。希望对您有所帮助!
阅读全文