用js写一个图片轮播页面
时间: 2023-12-11 16:04:49 浏览: 149
好的,我们可以通过以下步骤来实现一个简单的图片轮播页面:
1. 在html文件中添加轮播图片的div容器和左右切换按钮:
```html
<div class="slider">
<div class="slides">
<img src="image1.jpg" alt="Slide 1">
<img src="image2.jpg" alt="Slide 2">
<img src="image3.jpg" alt="Slide 3">
</div>
<div class="buttons">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
</div>
```
2. 在CSS文件中设置轮播容器的样式和动画效果:
```css
.slider {
position: relative;
width: 100%;
height: 500px;
overflow: hidden;
}
.slides {
display: flex;
width: 300%;
animation: slide 1s infinite;
}
.slides img {
width: 33.333%;
height: 100%;
object-fit: cover;
}
.buttons {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
button {
background-color: transparent;
border: none;
color: #fff;
font-size: 24px;
cursor: pointer;
}
@keyframes slide {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-200%);
}
}
```
3. 在JavaScript文件中添加按钮点击事件和自动轮播效果:
```javascript
const slides = document.querySelector('.slides');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let slideIndex = 0;
prevBtn.addEventListener('click', () => {
slideIndex--;
if (slideIndex < 0) {
slideIndex = 2;
}
slides.style.transform = `translateX(-${slideIndex * 100}%)`;
});
nextBtn.addEventListener('click', () => {
slideIndex++;
if (slideIndex > 2) {
slideIndex = 0;
}
slides.style.transform = `translateX(-${slideIndex * 100}%)`;
});
setInterval(() => {
slideIndex++;
if (slideIndex > 2) {
slideIndex = 0;
}
slides.style.transform = `translateX(-${slideIndex * 100}%)`;
}, 3000);
```
这样就完成了一个简单的图片轮播页面。
阅读全文