一个简单的轮播图组件
效果图
点击查看效果图html部分
<!-- 轮播组件容器 -->
<div class="lunbo-wrap pink">
<!-- 封面容器 -->
<div class="lunbo-img-wrap">
<img src="http://www.fashengwang.com/image/main_advertise.png" alt="" class="lunbo-img active">
<img src="http://www.fashengwang.com/image/main_advertise_2.png" alt="" class="lunbo-img">
<img src="http://www.fashengwang.com/image/main_advertise_3.png" alt="" class="lunbo-img">
</div>
<!-- 按钮容器 -->
<div class="lunbo-btn-wrap">
<span class="lunbo-btn active"></span>
<span class="lunbo-btn"></span>
<span class="lunbo-btn"></span>
</div>
</div>
- css部分
.lunbo-wrap {
position: relative;
width: 100%;
height: 350px;
transition: background-color 1s;
}
.lunbo-wrap.blue {
background-color: #ad7fec;
}
.lunbo-wrap.pink {
background-color: pink;
}
.lunbo-wrap.green {
background-color: #45c5d6;
}
.lunbo-img-wrap {
position: relative;
max-width: 1200px;
height: 100%;
margin: 0 auto;
}
.lunbo-img {
position: absolute;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.lunbo-img.active {
opacity: 1;
}
.lunbo-btn-wrap {
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
}
.lunbo-btn {
display: inline-block;
width: 15px;
height: 15px;
border-radius: 50%;
border: 1px solid;
margin-right: 10px;
cursor: pointer;
}
.lunbo-btn.active {
background-color: #333;
}
- js部分,es6语法
/**
* 轮播图组件
*/
class MyLunBo {
constructor () {
this.init()
}
init () {
this.lunboWrap = document.querySelector('.lunbo-wrap')
this.lunboImg = document.querySelectorAll('.lunbo-img')
this.lunboBtn = document.querySelectorAll('.lunbo-btn')
// 当前显示的索引
this.curr = 0
// 索引对应的颜色类
this.map = {
0: 'pink',
1: 'violet',
2: 'blue'
}
// 保存timeoutId,3s后开始切换
this.timeoutId = setTimeout(this.start.bind(this), 3000)
this.event()
}
start () {
let i = this.curr + 1
// 超出最大值归零
i > this.lunboImg.length - 1 ? i = 0 : ''
// 显示下一张
this.active(i)
// 递归
this.timeoutId = setTimeout(this.start.bind(this), 3000)
}
// 事件
event () {
const len = this.lunboBtn.length
for (let i = 0; i < len; i++) {
// 鼠标经过按钮,停止播放
this.lunboBtn[i].addEventListener('mouseover', () => {
this.active(i)
// 停止播放
clearTimeout(this.timeoutId)
})
// 鼠标离开,继续播放
this.lunboBtn[i].addEventListener('mouseout', () => {
// 重新播放
this.timeoutId = setTimeout(this.start.bind(this), 3000)
})
}
}
active (index) {
// 要切换的和当前的不同
if (index !== this.curr) {
// 显示当前图片
this.lunboImg[index].classList.add('active')
this.lunboBtn[index].classList.add('active')
this.lunboWrap.classList.add(this.map[index])
// 隐藏上次显示的图片
this.lunboImg[this.curr].classList.remove('active')
this.lunboBtn[this.curr].classList.remove('active')
this.lunboWrap.classList.remove(this.map[this.curr])
// 更新当前显示的图片
this.curr = index
}
}
}
export default LunBo