1.轮播的实现原理是怎样的?如果让你来实现,你会抽象出哪些函数(or接口)供使用?(比如 play())
示意图
Paste_Image.png
1.核心思路
这是一组水平排列无限滚动的图片。向后滚时,当滚动到最后一张时,出现第一张的clone图片,并迅速将整个父容器切换到第一张原始图片的位置,向前滚时,当滚动到第一张时,出现最后一张的clone图片,并迅速将整个父容器切换到最后原始图片的位置
2.css
父容器以上级元素作绝对定位,并设置固定宽高
.carousal {
position: relative;
top: 200px;
height: 200px;
width: 300px;
margin: 0 auto;
overflow: hidden;
}
.carousal .img-ct {
position: absolute;
width: 1200px;
}
子元素在父容器中水平排列,这里用浮动,图片以固定宽高展示
.carousal .img-ct li{
float: left;
}
.carousal .img-ct img {
width: 300px;
height: 200px;
}
3.javascript
1)安排完整队列:clone第一张和最后一张图片,并将其添加到子元素队列中去
var $firstImg = $imgCt.children('li').first(),
$lastImg = $imgCt.children('li').last()
$imgCt.prepend($lastImg.clone())
$imgCt.append($firstImg.clone())
2)更改位置:扩充父容器的宽度,使其包含伪装元素,并将位置前移到第一张原始图片的位置
$imgCt.width($firstImg.width()*$imgCt.children().length)
$imgCt.css('left', -$imgWidth)
抽离出核心函数:这是向后轮播的函数
function playNext(){
if(isAnimate) return;
isAnimate = true //设置的防重复点击的锁
$imgCt.animate({
left: '-=300' //向后移动位置
},'slow', function(){
currentIndex++;
if(currentIndex === $imgLength){
$imgCt.css('left', -$imgWidth) //滚动到最后一张向后切换时
回归第一张图片的位置
currentIndex = 0 //子元素标记重置为0
}
isAnimate = false //图片切换后解锁
setBullet() //图片切换后使下边缘小黑点跟随
})
}
图片下边缘动态框跟随图片动态变化函数
function setBullet(){
$bullet.children()
.removeClass('active')
.eq(currentIndex)
.addClass('active')
}