jquery+css实现简单的图片轮播效果

2020-05-22 15:22:46易采站长站整理

$(document).ready(function(){
var picNum = 4;//图片数量,根据实际修改
var picWidth = 1170;//图片的宽度,根据实际修改
var picMaxWidth = -1 * picNum * picWidth;
var currentPic = 1;
var next = $('#next');
var prev = $('#prev');
var flag = false;

prev.on('click',function(){
if(!flag){
calPx(1170);
currentPic--;
if (currentPic < 1) {
currentPic = picNum;
}
$('#buttons span').eq(currentPic-1).addClass('on').siblings().removeClass('on');
}
});

next.on('click',function(){
if(!flag){
calPx(-1170);
currentPic++;
if (currentPic > picNum) {
currentPic = 1;
}
$('#buttons span').eq(currentPic-1).addClass('on').siblings().removeClass('on');
}

});
$('.banner').on('mouseover',function(){
stop();
}).on('mouseout',function(){
play();
})
function nextClick(){
next.click();
}
function play(){
setInt = setInterval(nextClick,2000);
}
function stop(){
clearInterval(setInt);
}

function calPx(leftPx){
flag = true;
var left = parseInt($('.pic-list').css('left'));
var newLeft = left+leftPx;
var time = 300;
var interval = 10;
var speed = leftPx/(time/interval);

function go(){
var left = parseInt($('.pic-list').css('left'));
if((speed < 0 && left > newLeft) || (speed > 0 && left < newLeft)){
$('.pic-list').css('left', (left + speed) + 'px');
setTimeout(go,interval);
}else{
flag = false;
if( newLeft > -1170){
newLeft = picMaxWidth;
}else if (newLeft < picMaxWidth ) {
newLeft = -1170;
}
$('.pic-list').css('left',newLeft + 'px');
}
}
go();

}
play();

});