用js写一段轮播图代码
时间: 2023-12-18 11:53:10 浏览: 118
js轮播图代码
以下是一段基本的轮播图代码,使用了JavaScript和CSS实现:
HTML:
```html
<div class="slider">
<div class="slides">
<img src="image1.jpg" alt="" />
<img src="image2.jpg" alt="" />
<img src="image3.jpg" alt="" />
</div>
<div class="controls">
<span class="prev">Prev</span>
<span class="next">Next</span>
</div>
</div>
```
CSS:
```css
.slider {
position: relative;
overflow: hidden;
width: 500px;
height: 300px;
}
.slides {
display: flex;
width: 300%;
}
.slides img {
width: 500px;
height: 300px;
}
.controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.controls span {
display: inline-block;
padding: 10px 20px;
background-color: #000;
color: #fff;
cursor: pointer;
}
.controls .next {
margin-left: 20px;
}
```
JavaScript:
```javascript
const slider = document.querySelector(".slider");
const slides = document.querySelector(".slides");
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
const slideWidth = slider.clientWidth;
let slideIndex = 1;
function showSlide(index) {
slides.style.transform = `translateX(-${slideWidth * (index - 1)}px)`;
}
function prevSlide() {
if (slideIndex > 1) {
slideIndex--;
} else {
slideIndex = 3;
}
showSlide(slideIndex);
}
function nextSlide() {
if (slideIndex < 3) {
slideIndex++;
} else {
slideIndex = 1;
}
showSlide(slideIndex);
}
prevBtn.addEventListener("click", prevSlide);
nextBtn.addEventListener("click", nextSlide);
showSlide(slideIndex);
```
这段代码实现了一个基本的轮播图效果,点击Prev和Next按钮可以切换图片。其中,showSlide函数用于显示指定的图片,prevSlide和nextSlide函数用于切换上一张和下一张图片,slideIndex变量用于记录当前显示的图片编号。
阅读全文