编写一段前端轮播图代码
时间: 2023-03-13 17:08:24 浏览: 78
jQuery美女网站图片轮播切换代码.zip
答:```
<div class="slider">
<div class="slide-item">
<img src="slide-1.jpg" alt="第一张轮播图">
</div>
<div class="slide-item">
<img src="slide-2.jpg" alt="第二张轮播图">
</div>
<div class="slide-item">
<img src="slide-3.jpg" alt="第三张轮播图">
</div>
</div>
<script type="text/javascript">
let slider = document.querySelector('.slider');
let slideItems = slider.querySelectorAll('.slide-item');
let currentSlideIndex = 0; function showSlide() {
slideItems.forEach(function(slideItem, i) {
if (i === currentSlideIndex) {
slideItem.style.display = 'block';
} else {
slideItem.style.display = 'none';
}
});
}
showSlide(); // 设置定时器,每隔3秒轮播一次
setInterval(function() {
currentSlideIndex++;
if (currentSlideIndex === slideItems.length) {
currentSlideIndex = 0;
}
showSlide();
}, 3000);
</script>
```
阅读全文