写一段原生js轮播图源码
时间: 2024-03-08 16:23:20 浏览: 154
好的,这是一个简单的原生JavaScript实现轮播图的代码:
HTML部分:
```html
<div class="slider">
<div class="slider-container">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<div class="slider-prev">❮</div>
<div class="slider-next">❯</div>
<div class="slider-dots">
<span class="slider-dot"></span>
<span class="slider-dot"></span>
<span class="slider-dot"></span>
</div>
</div>
```
CSS部分:
```css
.slider {
position: relative;
}
.slider-container {
display: flex;
width: 100%;
height: 100%;
overflow: hidden;
}
.slider-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
.slider-prev, .slider-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 1;
cursor: pointer;
font-size: 30px;
color: white;
user-select: none;
}
.slider-prev {
left: 0;
}
.slider-next {
right: 0;
}
.slider-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
.slider-dot {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 5px;
background-color: gray;
border-radius: 50%;
cursor: pointer;
}
.slider-dot.active {
background-color: white;
}
```
JavaScript部分:
```javascript
const sliderContainer = document.querySelector('.slider-container');
const slides = sliderContainer.querySelectorAll('img');
const prevBtn = document.querySelector('.slider-prev');
const nextBtn = document.querySelector('.slider-next');
const dotsContainer = document.querySelector('.slider-dots');
const dots = dotsContainer.querySelectorAll('.slider-dot');
let slideIndex = 0;
// 设置轮播图的初始状态,显示第一张图片
slides[slideIndex].style.display = 'block';
dots[slideIndex].classList.add('active');
// 点击下一张按钮,切换到下一张图片
nextBtn.addEventListener('click', () => {
slides[slideIndex].style.display = 'none';
dots[slideIndex].classList.remove('active');
slideIndex++;
if (slideIndex >= slides.length) {
slideIndex = 0;
}
slides[slideIndex].style.display = 'block';
dots[slideIndex].classList.add('active');
});
// 点击上一张按钮,切换到上一张图片
prevBtn.addEventListener('click', () => {
slides[slideIndex].style.display = 'none';
dots[slideIndex].classList.remove('active');
slideIndex--;
if (slideIndex < 0) {
slideIndex = slides.length - 1;
}
slides[slideIndex].style.display = 'block';
dots[slideIndex].classList.add('active');
});
// 点击圆点按钮,切换到对应的图片
dotsContainer.addEventListener('click', e => {
const dot = e.target.closest('.slider-dot');
if (dot) {
slides[slideIndex].style.display = 'none';
dots[slideIndex].classList.remove('active');
slideIndex = Array.from(dots).indexOf(dot);
slides[slideIndex].style.display = 'block';
dots[slideIndex].classList.add('active');
}
});
// 自动轮播,每5秒切换到下一张图片
setInterval(() => {
nextBtn.click();
}, 5000);
```
以上是一个基本的轮播图的实现,您可以根据需求进行修改和定制,希望能够帮助到您!
阅读全文