無縫輪播實戰心得
阿新 • • 發佈:2018-11-19
1、圖片:圖片在第一張圖前面放置最後一張圖,在最後一張圖後面放上第一張圖
<img src="images/3.jpg" class=" img-responsive ">
<img src="images/1.jpg" class=" img-responsive">
<img src="images/2.jpg" class=" img-responsive ">
<img src="images/3.jpg" class=" img-responsive ">
<img src="images/1.jpg" class =" img-responsive ">
2、寬度:包裹的圖片的父元素,寬度=(所有圖片寬度)*(所有圖片個數)
(注:在這裡我給自己挖了兩個大坑,第一,在除錯向後箭頭和向前箭頭時,無法做到無縫連線(原因我將來寬度設定=(圖片寬度*3));第二,動畫時,點擊向後箭頭到最後一張圖卻換至第一張時,出現空白區域(原因:總寬度=圖片寬度*4))
#roll{
position: absolute;z-index: 1;width: 500%;left: -100%;}
#roll img{float: left;}
3、圓點按鈕:計算移動距離值;結束後賦值圓點index
//點選時按鈕index值
let sum = $(item).attr('index');
//移動距離
let offset= -(width*(sum -index)) ;
//呼叫位移函式
animate(offset);
//將點選後按鈕index的值,賦值
index = sum;
4、動畫:每次位移量(speed)=位移長度/(設定總位移時間/每一次唯一的間隔),新增動畫函式狗go(), setTimeout呼叫自身,定時器判斷條件(向左:speed>0 && (現在的位置 <目標位置);向右:speed <0 && (現在位置 > 目標位置)
//移動偏移量
function animate(offset){
let newleft = parseInt($('#roll').css('left')) + offset ;
let time =300;//總的位移時間
let interval =10;//位移間隔時間
let speed = offset/(time/interval);//每次位移量
animated = true;
//動畫函式
function go(){
let nowLeft = parseInt($('#roll').css('left'));//現在的位置
if((speed > 0 && nowLeft < newleft)|| (speed < 0 && nowLeft > newleft)){//判斷是否達到目標值
$('#roll').css({'left':nowLeft+speed +'px'});
setTimeout(go,interval);
}else{
$('#roll').css({'left':newleft+'px'}) ;
if(newleft > - (width)){
$('#roll').css({'left':-(3*width)+'px'}) ;
}
if(newleft < (-3*width)){
$('#roll').css({'left':-width +'px'}) ;
}
}
animated =false;
}
go();
}
5、防止多次點擊出現多次動畫效果後的bug:設定正在點選的標誌位,go()函式執行完成之後設定為false;在設定點選事件時,判斷標誌位是否為真,if(true)return;
$('#next').click(() =>{
if (animated)return;
if(index == 3){index =1;
}else{index +=1;}
animate(-width);
showbotton(index);
});