写一个轮播图
时间: 2023-07-04 21:10:33 浏览: 43
好的,这里提供一个简单的轮播图示例,你可以根据自己的需求进行修改和扩展:
HTML:
```
<div class="slider">
<div class="slides">
<img src="img1.jpg">
<img src="img2.jpg">
<img src="img3.jpg">
</div>
<div class="controls">
<span class="prev"><</span>
<span class="next">></span>
</div>
</div>
```
CSS:
```
.slider {
position: relative;
overflow: hidden;
}
.slides {
display: flex;
width: 300%;
transition: transform 0.5s ease-in-out;
}
.slides img {
width: 33.3333%;
}
.controls {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
display: flex;
justify-content: space-between;
z-index: 10;
}
.controls span {
font-size: 2rem;
color: #fff;
cursor: pointer;
}
.controls span:hover {
color: #ccc;
}
.prev {
margin-left: 1rem;
}
.next {
margin-right: 1rem;
}
```
JavaScript:
```
const slider = document.querySelector('.slider');
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 * 33.3333}%)`;
});
nextBtn.addEventListener('click', () => {
slideIndex++;
if (slideIndex > 2) {
slideIndex = 0;
}
slides.style.transform = `translateX(-${slideIndex * 33.3333}%)`;
});
setInterval(() => {
slideIndex++;
if (slideIndex > 2) {
slideIndex = 0;
}
slides.style.transform = `translateX(-${slideIndex * 33.3333}%)`;
}, 5000);
```
此轮播图默认有三张图片,你可以自己添加或删除图片。同时,你可以根据自己的需要修改 CSS 样式,例如更改图片大小、颜色、字体等等。JavaScript 部分为轮播图的核心代码,实现了点击按钮和自动播放两种方式。你可以根据自己的需求进行修改和扩展。
阅读全文