写一个无缝轮播图
时间: 2023-07-04 13:13:12 浏览: 100
好的,以下是一个简单的无缝轮播图的实现代码:
HTML结构:
```
<div class="slider">
<div class="slider-wrapper">
<div class="slide"><img src="slide1.jpg"></div>
<div class="slide"><img src="slide2.jpg"></div>
<div class="slide"><img src="slide3.jpg"></div>
<div class="slide"><img src="slide4.jpg"></div>
<div class="slide"><img src="slide5.jpg"></div>
</div>
</div>
```
CSS样式:
```
.slider {
width: 100%;
overflow: hidden;
}
.slider-wrapper {
display: flex;
transition: transform 0.5s ease-in-out;
}
.slide {
flex-shrink: 0;
width: 100%;
}
.slide img {
width: 100%;
height: auto;
}
```
JavaScript代码:
```
const slider = document.querySelector('.slider');
const sliderWrapper = document.querySelector('.slider-wrapper');
const slides = document.querySelectorAll('.slide');
const slideWidth = slides[0].offsetWidth;
let currentIndex = 0;
sliderWrapper.style.width = slides.length * slideWidth + 'px';
setInterval(() => {
currentIndex++;
if (currentIndex >= slides.length) {
currentIndex = 0;
sliderWrapper.style.transition = 'none';
sliderWrapper.style.transform = `translateX(0)`;
} else {
sliderWrapper.style.transition = 'transform 0.5s ease-in-out';
sliderWrapper.style.transform = `translateX(-${currentIndex * slideWidth}px)`;
}
}, 3000);
```
这段代码会定时每隔3秒钟切换到下一张图片,当切换到最后一张图时,它会无缝地切换到第一张图,实现了无缝轮播的效果。
阅读全文