js輪播圖教程
阿新 • • 發佈:2019-02-16
window.onload = function() {
var list = document.getElementById('list');
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var box = document.getElementById('box');
function animate(offset) {
//獲取的是style.left,是相對左邊獲取距離,所以第一張圖後style.left都為負值,
//且style.left獲取的是字串,需要用parseInt()取整轉化為數字。
var newLeft = parseInt(list.style.left) + offset;
if(newLeft < -11520){
newLeft = -3840;
}//當到邊界時, 返回圖片的當前位置
if(newLeft > 0){
newLeft = -7680 ;
}
list.style.left = newLeft + 'px';
}
// prev.onclick = function() {
// animate(1920);
// }
// next.onclick = function() {
// animate(-1920);
// }
var timer;
function play() {//設定定時器
timer = setInterval(function () {
next.onclick()
}, 1500)
}
play();
function stop() {
clearInterval(timer);
}
box.onmouseover = stop;
box.onmouseout = play;
var buttons = document.getElementById('buttons').getElementsByTagName('li');
var index = 1;
function buttonsShow() {
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].className == 'on') {
buttons[i].className = '';
}
}//遍歷找到有class為on的li, 並清除掉
buttons[index-1].className = 'on';
}
prev.onclick = function() {
index--;
if (index < 1) {
index = 5;
}
buttonsShow();
animate(1920);
}
next.onclick = function() {
index++;
if (index > 5) {
index = 1;
}
buttonsShow();
animate(-1920);
}
for (var i = 0; i < buttons.length; i++) {//下面由於產生了一個典型的閉包, 因此要採用立即執行函式的方法
(function(j){
buttons[j].onclick = function () {
console.log(j);
var clickIndex = parseInt(this.getAttribute('index'));
var offset = 1920 * (index - clickIndex);
animate(offset); //存放滑鼠點選後的位置,用於小圓點的正常顯示
index = clickIndex;
buttonsShow();
}
})(i)
}
}