js写一个图片轮播页面
时间: 2023-12-12 14:05:27 浏览: 72
图片轮播 js
好的,以下是一个简单的图片轮播页面的实现:
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="prev"><</div>
<div class="next">></div>
</div>
```
CSS:
```css
.slider {
position: relative;
width: 100%;
overflow: hidden;
}
.slides {
display: flex;
width: 300%;
}
.slides img {
width: 33.33%;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
font-weight: bold;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
```
JavaScript:
```javascript
const slider = document.querySelector('.slider');
const slides = document.querySelector('.slides').children;
const prev = document.querySelector('.prev');
const next = document.querySelector('.next');
let index = 0;
prev.addEventListener('click', () => {
index--;
if (index < 0) {
index = slides.length - 1;
}
slide();
});
next.addEventListener('click', () => {
index++;
if (index >= slides.length) {
index = 0;
}
slide();
});
function slide() {
for (let i = 0; i < slides.length; i++) {
slides[i].classList.remove('active');
}
slides[index].classList.add('active');
slider.style.transform = `translateX(-${index * 100 / slides.length}%)`;
}
slide();
```
这个实现方式使用了 flex 布局和 translateX 实现轮播,点击 prev 和 next 按钮可以切换图片。
阅读全文