麻烦用JavaScript写一个轮播图,
时间: 2023-12-29 07:18:50 浏览: 75
好的,以下是一个简单的JavaScript轮播图实现:
HTML代码:
```html
<div class="slider">
<img src="image1.jpg" alt="image1">
<img src="image2.jpg" alt="image2">
<img src="image3.jpg" alt="image3">
</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.active {
opacity: 1;
}
```
JavaScript代码:
```javascript
const slider = document.querySelector('.slider');
const images = document.querySelectorAll('.slider img');
let currentImage = 0;
let interval;
function startSlider() {
interval = setInterval(() => {
images[currentImage].classList.remove('active');
currentImage = (currentImage + 1) % images.length;
images[currentImage].classList.add('active');
}, 2000);
}
function stopSlider() {
clearInterval(interval);
}
slider.addEventListener('mouseenter', stopSlider);
slider.addEventListener('mouseleave', startSlider);
startSlider();
```
这段代码会创建一个包含三张图片的轮播图,每隔两秒钟自动切换到下一张图片,并且当鼠标悬停在轮播图上时停止自动播放。
阅读全文