輪播原生js封裝
總共四個(gè)部分
標(biāo)題
*{
margin:0;
padding:0;
}
ul{
list-style:none;
}
.list img{
width:100%;
vertical-align:top;
}
.box{
width:800px;
height:450px;
margin:50px auto;
overflow:hidden;
position:relative;
}
.list{
width:800%;
height:450px;
position:absolute;
left:0;
top:0;
transition:all.5s;
}
.list li{
float:left;
width:800px;
height:450px;
}
.box span{
display:inline-block;
width:40px;
height:80px;
position:absolute;
top:50%;
margin-top: -40px;
background-color:rgba(51,51,51,0.5);
cursor:pointer;
}
.back{
left:0;
}
.next{
right:0;
}
.point{
position:absolute;
bottom:20px;
right:100px;
}
.point li{
float:left;
width:20px;
height:20px;
border-radius:50%;
cursor:pointer;
background-color:#000;
margin-left:20px;
}
.point.active{
background-color:#01ffff;
}
var_box=document.getElementById('box');//最大容器
var_list=document.getElementById('list');//? ul
var_li=_list.getElementsByTagName('li');//li
var_back=document.getElementById('back');//上一頁
var_next=document.getElementById('next');//下一頁
var_point=document.getElementById('point');//小圓點(diǎn)的ul
var_ali=_point.getElementsByTagName('li');//小圓點(diǎn)
variNow=0;
vartimer=null;
// 第一部分:
// 獲取變量暫時(shí)不提,接下來的輪播第一步:先自己封裝一個(gè)函數(shù),如下:
functionmove(){
// 自己封裝的函數(shù)內(nèi)執(zhí)行一個(gè)for循環(huán),該循環(huán)是動(dòng)態(tài)給 圓點(diǎn)(li)通過動(dòng)態(tài)添加class名
// 然后在css樣式中寫li的背景顏色樣式改變它的背景顏色。
for(vari=0;i<_ali.length;i++){
// 讓圓點(diǎn)(li)的class名為空。
_ali[i].className='';
}
// 讓當(dāng)前的li圓點(diǎn)添加class名稱
_ali[iNow].className='active';
// 讓整個(gè)ul向左慢慢移動(dòng),移動(dòng)的距離就是當(dāng)前l(fā)i的寬度這個(gè)寬度是慢慢增加的。
_list.style.left=-_li[0].offsetWidth*iNow+'px';
}
// 第二部分:主要是點(diǎn)擊事件。
// 給我們的左右點(diǎn)擊按鈕添加點(diǎn)擊事件 通過我們的點(diǎn)擊按鈕的點(diǎn)擊事件改變兩件事,一:就是讓我們的輪播圖片執(zhí)行,也就是執(zhí)行我們封裝好的函數(shù)
// 二:讓我們的小圓點(diǎn)相對(duì)應(yīng)的執(zhí)行。
_next.onclick=function(){
iNow++;
if(iNow>=_li.length){
iNow=0;
}
move()
}
_back.onclick=function(){
iNow--;
if(iNow<=-1){
iNow=_li.length-1;
}
move()
}
// 接下來就是讓輪播中的小點(diǎn) 點(diǎn)擊讓相應(yīng)的圖片進(jìn)行變換
for(vari=0;i<_ali.length;i++){
// 先動(dòng)態(tài)獲取我們的小點(diǎn)歲所對(duì)應(yīng)的li,
_ali[i].index=i;
//給我們的小點(diǎn)添加點(diǎn)擊事件
//點(diǎn)擊圓圈讓我們的輪播執(zhí)行。
_ali[i].onclick=function(){
//讓我們的變量iNow變成當(dāng)前的小圓點(diǎn)。
iNow=this.index;
//執(zhí)行我們之前封裝好的move函數(shù)
move()
}
}
move();
// 接下來就是第三部分:清除定時(shí)器:clearInterval(timer)
clearInterval(timer)
// setInterval 無限執(zhí)行;在我們清除定時(shí)器的時(shí)候,想讓定時(shí)器無限執(zhí)行,執(zhí)行到達(dá)一定地步的時(shí)候再清除。也就是說讓我們inow一直執(zhí)行 當(dāng)其小于li標(biāo)簽的個(gè)數(shù)(長(zhǎng)度)的時(shí)候再歸0.當(dāng)然這個(gè)過程就是我們輪播圖片切換的過程。執(zhí)行時(shí)間是2秒。
timer=setInterval(function(){
iNow++;
if(iNow>=_li.length){
iNow=0;
}
move()
},2000)
// 第四部分:鼠標(biāo)移入移除效果:而鼠標(biāo)移入移除的范圍就是在我們?cè)O(shè)定的div塊元素中。
// 鼠標(biāo)移入的時(shí)候清除定時(shí)器。
_box.onmouseover=function(){
clearInterval(timer);
}
// 鼠標(biāo)移除的時(shí)候開始執(zhí)行定時(shí)器功能。
_box.onmouseout=function(){
clearInterval(timer);
timer=setInterval(function(){
iNow++;
if(iNow>=_li.length){
iNow=0;
}
move()
},2000)
}