用Javascript写一个轮播图
时间: 2024-05-02 17:22:57 浏览: 100
好的,以下是一个简单的轮播图实现方案:
HTML结构:
```html
<div class="slider-container">
<div class="slider">
<img src="img/slider-img-1.jpg" alt="slide 1" />
<img src="img/slider-img-2.jpg" alt="slide 2" />
<img src="img/slider-img-3.jpg" alt="slide 3" />
<img src="img/slider-img-4.jpg" alt="slide 4" />
</div>
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
```
CSS样式:
```css
.slider-container {
position: relative;
}
.slider {
display: flex;
overflow: hidden;
width: 100%;
}
.slider img {
flex-shrink: 0;
width: 100%;
height: auto;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
border: none;
background: transparent;
color: #fff;
font-size: 1.5em;
cursor: pointer;
}
.prev {
left: 2%;
}
.next {
right: 2%;
}
```
JavaScript代码:
```javascript
// 获取元素
const sliderContainer = document.querySelector(".slider-container");
const slider = document.querySelector(".slider");
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
const slides = document.querySelectorAll(".slider img");
const slideWidth = slides[0].clientWidth;
let slideIndex = 0;
// 将最后一张图片拷贝到开头处,实现循环
slider.prepend(slides[slides.length - 1].cloneNode(true));
slider.style.transform = `translateX(${-slideWidth}px)`;
// 定义前进和后退的函数
function prev() {
if (slideIndex === 0) {
slideIndex = slides.length - 1;
} else {
slideIndex--;
}
slider.style.transform = `translateX(${-slideWidth * (slideIndex + 1)}px)`;
}
function next() {
if (slideIndex === slides.length - 1) {
slideIndex = 0;
} else {
slideIndex++;
}
slider.style.transform = `translateX(${-slideWidth * (slideIndex + 1)}px)`;
}
// 添加前进和后退按钮的点击事件
prevBtn.addEventListener("click", prev);
nextBtn.addEventListener("click", next);
// 自动播放
setInterval(next, 5000);
```
阅读全文