** 1、 輪播的實現(xiàn)原理是怎樣的?如果讓你來實現(xiàn),你會抽象出哪些函數(shù)(or接口)供使用?(比如 play())**####
輪播實現(xiàn)原理:
1.將圖片排成一行;
2.創(chuàng)建一個可視化窗口,窗口之外的區(qū)域隱藏;
3.在第一張圖片的前面克隆最后一個圖片元素,在最后一個圖片后面克隆第一個元素;
4.利用jQuery動畫以及定位就能實現(xiàn)無限循環(huán)的輪播;
我們可以抽象出來的代碼有很多,比如antoPlay()、playNext()、playPre()
(比如play)
實現(xiàn)一個play(index)函數(shù)
傳入要顯示的圖片頁數(shù)
function play(index){
if(curPageIndex === index){
return;
}
if(isAnimate) return;
isAnimate = true;
$imgCt.animate({
left: '+=' + (curPageIndex - index) * $firstImg.width()
}, function(){
curPageIndex = index;
if(curPageIndex === imgLength){
$imgCt.css({
left: - $firstImg.width()
})
curPageIndex = 0;
}
else if(curPageIndex === -1){
$imgCt.css({
left: - $firstImg.width() * imgLength
})
curPageIndex = imgLength -1 ;
}
isAnimate = false;
})
}
輪播的基本原理是先并列要輪播的東西,然后設(shè)置為不可見或在可見區(qū)域之外,最后按順序使之可見或者移放至可見區(qū)域之內(nèi)。以上就是核心代碼的思想,可封裝為一個函數(shù)。