Justin's Words

JavaScript Carousel

明天还要上课先睡觉,明天再写过程。



var container = document.getElementsByClassName('container')[0],
carousel = document.getElementsByClassName('carousel')[0],
btns = document.getElementsByClassName('slide');
prev = document.getElementsByClassName('prev')[0],
next = document.getElementsByClassName('next')[0],
index = 1,
animated = false,
interval = 2000;
timer = 0,
itemHeight = 80;

carousel.scrollTop = 0;

window.onload = function () {
carousel.scrollTop += itemHeight;
}

prev.onclick = function () {
if (animated) {
return;
}
index–;
if (index > btns.length) {
index = 1;
} else if (index < 1) {
index = btns.length;
}
animate(-itemHeight);
showBtn();
}

next.onclick = function () {
if (animated) {
return;
}
index++;
if (index > btns.length) {
index = 1;
} else if (index < 1) {
index = btns.length;
}
animate(itemHeight);
showBtn();
}

for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
if (index === (i + 1) || animated) {
return;
}
var myIndex = parseInt(this.getAttribute('index'));
var offset = itemHeight (myIndex - index);

animate(offset);
index = myIndex;
showBtn();
}
}

function animate(offset) {
var time = 300,
interval = 10,
speed = offset/(time/interval),
newTop = carousel.scrollTop + offset;

animated = true;

var go = function() {
if ((speed > 0 && carousel.scrollTop < newTop) || (speed < 0 && carousel.scrollTop > newTop)) {
carousel.scrollTop += speed;
setTimeout(go, interval);
} else {
carousel.scrollTop = newTop;
if (carousel.scrollTop < itemHeight) {
carousel.scrollTop = itemHeight
4;
} else if (carousel.scrollTop > itemHeight * 4) {
carousel.scrollTop = itemHeight;
}
animated = false;
}
}

go();
}

function showBtn() {
for (var i = 0; i < btns.length; i++) {
if (btns[i].className === 'slide on') {
btns[i].className = 'slide';
break;
}
}
btns[index-1].className = 'slide on';
}

function play() {
timer = setTimeout(function () {
next.onclick();
play();
}, interval);
}

function stop() {
clearTimeout(timer);
}

container.onmouseover = stop;
container.onmouseout = play;

play();

See the Pen XJdBbz by Justin Young (@youngdze) on CodePen.