js中用面向对象的思想——淡入淡出轮播图

时间:2021-06-03 23:14:51

首先看下效果图js中用面向对象的思想——淡入淡出轮播图

明确功能 1.前后切换(边界判断) 2.按键切换  3.自动轮播

css代码

<style>
* {margin:0; padding:0;}
li{list-style:none; } #div1 {width:850px; height:500px; margin:50px auto; overflow:hidden; position:relative;}
#div1 ul li{height:500px;opacity: 0;position: absolute;left: 0;top: 0;z-index: 0;transition: opacity 1.5s;}
#div1 ul li.ac{z-index: 5;opacity: 1;}
#div1 ol {position:absolute;right: 10%;bottom: 10px;z-index:6}
#div1 ol li{width: 20px;height: 20px;background: #fff;margin-left: 5px;float: left;line-height: 20px;text-align: center;cursor: pointer;}
#div1 ol li.ac{background: red;color: #fff;}
#div1>a{text-decoration: none;position: absolute;top: 50%;margin-top: -10px;height: 40px;line-height: 32px;text-align: center;width: 40px;font-size: 40px;vertical-align: middle;color: #fff;background: rgba(0,0,0,0.5);z-index:6;}
#goPrev{left: 0;}
#goNext{right: 0;}
img{width:850px; height:500px;}
</style>

body中的代码

 <div id="div1">
<ul>
<li class="ac"><a href="javascript:alert(0);"><img src="/1.jpg" /></a></li>
<li><a href="javascript:alert(1);"><img src="/2.jpg" /></a></li>
<li><a href="javascript:alert(2);"><img src="/3.jpg" /></a></li>
<li><a href="javascript:alert(3);"><img src="/4.jpg" /></a></li>
<li><a href="javascript:alert(4);"><img src="/5.jpg" /></a></li>
</ul>
<ol>
<li class="ac">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<a href="javascript:;" id="goPrev">&laquo;</a>
<a href="javascript:;" id="goNext">&raquo;</a>
</div>

js代码

 class LB{

         constructor(){

             this.div = document.querySelector('#div1'),
this.imgs = this.div.querySelectorAll('ul li'),
this.btns = this.div.querySelectorAll('ol li'),
this.goPrev = document.querySelector('#goPrev'),
this.goNext = document.querySelector('#goNext'); this.iNow = 0
this.iLast = 0
this.timer = null this.BtnsEvent()
this.goEvent()
this.gotimer() } BtnsEvent(){ Array.from(this.btns).forEach((btns,i) => { this.btns[i].onclick = () => {
this.iLast = this.iNow
this.iNow = i
this.change()
}
})
} goEvent(){ //向->切换
this.goNext.onclick = () => { this.iLast = this.iNow
this.iNow == this.btns.length-1? this.iNow=0:this.iNow++
this.change()
} //向<-切换
this.goPrev.onclick = () => { this.iLast = this.iNow
this.iNow == 0? this.iNow=this.btns.length-1:this.iNow--
this.change()
} } gotimer(){ this.timer = setInterval(this.goNext.onclick,2000) this.div.onmouseenter = () => {
clearInterval(this.timer)
} this.div.onmouseleave = () => { this.timer = setInterval(this.goNext.onclick,2000)
}
} //更改图片
change(){ this.btns[this.iLast].className = ''
this.imgs[this.iLast].className = ''
this.btns[this.iNow].className = 'ac'
this.imgs[this.iNow].className = 'ac' } } var lb =new LB('#div1')

效果已实现

js中用面向对象的思想——淡入淡出轮播图