简易的轮播图
时间: 2023-07-23 12:09:09 浏览: 82
好的,以下是一个简易的轮播图的实现方式:
HTML:
```html
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
```
CSS:
```css
.slider {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.slider img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slider img:first-child {
opacity: 1;
}
.slider img.active {
opacity: 1;
}
.slider .prev, .slider .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
text-align: center;
line-height: 50px;
cursor: pointer;
}
.slider .prev {
left: 0;
}
.slider .next {
right: 0;
}
```
JS:
```js
const slider = document.querySelector('.slider');
const slides = slider.querySelectorAll('img');
const prev = slider.querySelector('.prev');
const next = slider.querySelector('.next');
let activeSlide = 0;
function showSlide(n) {
slides[activeSlide].classList.remove('active');
slides[n].classList.add('active');
activeSlide = n;
}
function prevSlide() {
let n = activeSlide - 1;
if (n < 0) {
n = slides.length - 1;
}
showSlide(n);
}
function nextSlide() {
let n = activeSlide + 1;
if (n >= slides.length) {
n = 0;
}
showSlide(n);
}
prev.addEventListener('click', prevSlide);
next.addEventListener('click', nextSlide);
setInterval(nextSlide, 5000);
```
以上代码实现了一个基本的轮播图,可以通过 CSS 自定义轮播图的样式,通过 JS 实现轮播图的切换。其中,通过 setInterval 方法可以定时切换轮播图。
阅读全文