帮我写一个轮播图代码
时间: 2023-08-28 14:16:50 浏览: 94
好的,以下是一个简单的轮播图代码示例:
HTML部分:
```html
<div class="slider">
<div class="slider-wrapper">
<img src="img1.jpg" alt="Image 1">
<img src="img2.jpg" alt="Image 2">
<img src="img3.jpg" alt="Image 3">
</div>
<a href="#" class="slider-prev"><</a>
<a href="#" class="slider-next">></a>
</div>
```
CSS部分:
```css
.slider {
position: relative;
overflow: hidden;
}
.slider-wrapper {
display: flex;
width: 100%;
transition: transform 0.5s ease-in-out;
}
.slider-wrapper img {
width: 100%;
height: auto;
}
.slider-prev,
.slider-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 2rem;
color: #fff;
text-decoration: none;
z-index: 1;
}
.slider-prev {
left: 20px;
}
.slider-next {
right: 20px;
}
```
JavaScript部分:
```javascript
const sliderWrapper = document.querySelector('.slider-wrapper');
const sliderPrev = document.querySelector('.slider-prev');
const sliderNext = document.querySelector('.slider-next');
const sliderImages = document.querySelectorAll('.slider-wrapper img');
let currentIndex = 0;
const slideWidth = sliderImages[0].clientWidth;
sliderPrev.addEventListener('click', () => {
currentIndex = (currentIndex === 0) ? sliderImages.length - 1 : currentIndex - 1;
sliderWrapper.style.transform = `translateX(-${currentIndex * slideWidth}px)`;
});
sliderNext.addEventListener('click', () => {
currentIndex = (currentIndex === sliderImages.length - 1) ? 0 : currentIndex + 1;
sliderWrapper.style.transform = `translateX(-${currentIndex * slideWidth}px)`;
});
```
这段代码实现了一个基本的轮播图,其中图片的数量可以根据需要进行调整。
阅读全文