请使用原生js实现轮播图
时间: 2024-05-13 07:21:02 浏览: 80
以下是一个简单的原生js轮播图实现:
HTML代码:
```html
<div id="slider">
<img src="img1.jpg" alt="">
<img src="img2.jpg" alt="">
<img src="img3.jpg" alt="">
</div>
```
CSS代码:
```css
#slider {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
#slider img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
#slider img.active {
opacity: 1;
}
```
JavaScript代码:
```javascript
var slider = document.getElementById('slider');
var images = slider.getElementsByTagName('img');
var current = 0;
function slide() {
// 隐藏当前图片
images[current].classList.remove('active');
// 计算下一张图片的索引
current = (current + 1) % images.length;
// 显示下一张图片
images[current].classList.add('active');
}
// 每3秒钟自动切换图片
setInterval(slide, 3000);
```
上述代码实现了一个简单的自动轮播图,每3秒钟自动切换一张图片。可以根据需要添加其他功能,如左右箭头切换、圆点导航等。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![html](https://img-home.csdnimg.cn/images/20241231044918.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)