第一步:实现无操作的自动轮播 (四张图)
function slider() {
timer = setTimeout(function () {
$('.img-box').animate({ 'left': -(nowIndex * picwidth) + 'px' },function(){
nowIndex++
if (nowIndex == 5) {
$('.img-box').css('left', '0px');
nowIndex = 1;
slider()
} else {
slider()
}
})
}, 1000)
}
问题小结:animate在执行的过程中就会执行下面的代码(不包括回调函数的内容),这样想对运动中的一些状态和相关值的修改(如left)是无效的
html和css样式代码就不放了,
时间1531759248287
点击事件的加入
左右按钮,索引按钮。
左按钮:切换前一张图片(当图片为第一张时,点击左需要切换到最后一张)
右按钮:切换下一张图片(当图片为最后一张时候切换到第一张)
索引按钮:点击哪个索引按钮,切换到索引对应的图片内容
遇见问题一:多个class时候点点击事件class怎么书写
遇见问题二:缓冲图片(视觉连续)
遇见问题三:定时器在执行清除不掉
遇见问题四:运动叠加
遇见问题五:自动运动内涵
实现代码去耦合
$('.wrapper').on('mouseenter', function () {
console.log(timer);
clearTimeout(timer);
}).on('mouseleave', function () {
sliderAuto();
})
var len = 4;
var nowIndex = 0;
var picwidth = 600;
var timer;
var flag = true;
function init() {
//自动轮播
sliderAuto();
//实现点击事件
bindEvent();
}
init();
function bindEvent() {
$('.order li').add('.Dleft').add('.Dright').on('click', function () {
if ($(this).attr('class') == 'btn Dleft') {
//点击左,页面向左移
move('Dleft');
} else if ($(this).attr('class') == 'btn Dright') {
//点击右,页面向右移
move('Dright');
} else {
//点击索引圆点,往特定的索引切换
move($(this).index());
changeStyle()
}
})
}
function move(dir) {
if (flag) {
flag = false;//防止运动叠加
if (dir == 'Dleft') {
if (nowIndex == 0) {
$('.img-box').css('left', -len * picwidth + 'px');//缓冲跳到最后
nowIndex = len - 1;
} else {
nowIndex--;
}
} else if (dir == 'Dright') {
if (nowIndex == len - 1) {
$('.img-box').animate({ 'left': -(len * picwidth) + 'px' }, function () {
$('.img-box').css('left', '0');
})
nowIndex = 0;
} else {
nowIndex++;
}
} else {
nowIndex = dir;
}
slider();
changeStyle()
}
}
function slider() {
$('.img-box').animate({ 'left': -(nowIndex * picwidth) + 'px' }, function () {
flag = true;
})
}
function changeStyle() {
//切换class
$('.active').removeClass('active');
$('.order ul li').eq(nowIndex).addClass('active');
}
function sliderAuto() {
console.log(nowIndex);
clearTimeout(timer);
timer = setTimeout(function () {
move('Dright');
sliderAuto();
}, 2000)
}