es6 透明度轮播图
效果图
html结构
<div class="wrap">
<div class="show">
<img class="imgShow" src="./images/1.png" alt="">
<img src="./images/2.png" alt="">
<img src="./images/6.png" alt="">
<img src="./images/4.png" alt="">
<img src="./images/5.png" alt="">
</div>
<p class="prev"></p>
<p class="next"></p>
<ul class="num">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
css样式
轮播图具体样式看个人喜好,但图片必须用绝对定位重叠在一起,在于图片其他样式以及上一张,下一张,图片序号可以自己定义,这里js代码中需要用到两个样式
.wrap .show .imgShow {
z-index: 20;
}
.wrap .num .active {
background-color: lightseagreen;
}
active状态的样式也可以自己定义
调用方式
new Banner({
img: ".show img",
number: ".num li",
prev:'.prev',
next:'.next'
})
js代码
这里需要用到我封装的animate函数,csdn地址:animate函数
class Banner {
constructor(option) {
this.init(option)//初始化
}
init(option) {
this.imgAll = document.querySelectorAll(option.img);
this.numAll = document.querySelectorAll(option.number);
this.prev = document.querySelector(option.prev);
this.next = document.querySelector(option.next);
this.index = 0;//默认展示项
this.timer = null;
animate(this.imgAll[this.index], {//轮播图实例化后第一张图片透明度开始变化
opacity: 1
}, () => {//启动轮播,时间间隔3秒
this.auto()
});
this.bindEvent();
}
auto(){//启动轮播,时间间隔3秒
this.timer = setInterval(() => {
this.moveNext()
}, 3000)
}
clearTimer(){
clearInterval(this.timer);//清除自动轮播定时器
clearInterval(this.imgAll[this.index].timer);//清除当前透明度变化定时器
}
initStyle(){
this.imgAll[this.index].className = '';//默认样式
this.numAll[this.index].className = '';
this.imgAll[this.index].style.opacity = 0.2
}
addStyle(){//显示样式
this.numAll[this.index].className = 'active';
this.imgAll[this.index].className = 'imgShow'
animate(this.imgAll[this.index], {
opacity: 1
});
}
bindEvent() {
if (this.prev) {//如果传了上一张按钮
this.prev.onclick = () => {
this.clearTimer()//清除定时器
this.moveNPrev();//图片切换到上一张
this.auto()//启动轮播,时间间隔3秒
}
}
if (this.next) {
this.next.onclick = () => {
this.clearTimer()
this.moveNext();//图片切换到下一张
this.auto()//启动轮播,时间间隔3秒
}
}
if (this.numAll) {
for (let i = 0, n = this.numAll.length; i < n; i++) {
this.numAll[i].onclick = () => {
this.clearTimer()//清除定时器
this.moveIndex(i)//跳转到指定图片
this.auto()//启动轮播,时间间隔3秒
}
};
}
}
moveIndex(newIndex) {
this.initStyle()//恢复上一张默认样式
this.index = newIndex;//指定索引
this.addStyle()//添加显示样式
}
moveNext() {
this.initStyle()//恢复上一张默认样式
this.index++;//下一张图片
if (this.index >= this.imgAll.length) {//临界值判断
this.index = 0;
}
this.addStyle()//添加显示样式
}
moveNPrev() {
this.initStyle()//恢复上一张默认样式
this.index--;//上一张图片
if (this.index < 0) {//临界值判断
this.index = this.imgAll.length - 1;
}
this.addStyle()//添加显示样式
}
}