请用js原生写一个轮播图
时间: 2024-04-30 15:17:16 浏览: 101
原生js实现轮播图的示例代码
好的,以下是一个简单的用原生js实现的轮播图:
HTML代码:
```html
<div class="slider">
<ul class="slides">
<li><img src="https://picsum.photos/id/1/800/400" alt="Slide 1"></li>
<li><img src="https://picsum.photos/id/2/800/400" alt="Slide 2"></li>
<li><img src="https://picsum.photos/id/3/800/400" alt="Slide 3"></li>
</ul>
</div>
<button class="prev">Previous slide</button>
<button class="next">Next slide</button>
```
CSS代码:
```css
.slider {
position: relative;
}
.slides {
list-style: none;
margin: 0;
padding: 0;
position: relative;
}
.slides li {
position: absolute;
left: 0;
top: 0;
opacity: 0;
transition: opacity 1s ease-out;
}
.slides li:first-child {
opacity: 1;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
border: none;
background: transparent;
outline: none;
cursor: pointer;
}
.prev {
left: 20px;
}
.next {
right: 20px;
}
```
JavaScript代码:
```javascript
const slides = document.querySelectorAll('.slides li');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentIndex = 0;
// 显示当前索引的幻灯片
function showSlide(index) {
// 将所有幻灯片的不透明度设置为0
slides.forEach(slide => {
slide.style.opacity = 0;
});
// 将当前幻灯片的不透明度设置为1
slides[index].style.opacity = 1;
}
// 显示下一张幻灯片
function nextSlide() {
currentIndex++;
if (currentIndex >= slides.length) {
currentIndex = 0;
}
showSlide(currentIndex);
}
// 显示上一张幻灯片
function prevSlide() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = slides.length - 1;
}
showSlide(currentIndex);
}
// 添加按钮点击事件处理程序
prevBtn.addEventListener('click', prevSlide);
nextBtn.addEventListener('click', nextSlide);
```
以上代码将创建一个具有前进和后退按钮的简单幻灯片,导航按钮和计时器等其他功能可根据需要添加。
阅读全文