1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| //綁定圖片Box let img_box = document.querySelector('.img_box'); let imgs = document.querySelectorAll('img');
//綁定引導Box let sel_box = document.querySelector('.sel_box') let lis = sel_box.querySelectorAll('li');
//左右按鈕 let left_btn = document.querySelector('.left_btn'); let right_btn = document.querySelector('.right_btn');
//索引第幾張 let index = 0; let timer = null;
//設置容器大小 let imgContainerW = img_box.offsetWidth img_box.style.width = imgContainerW * imgs.length + 'px' //設置容器位置 img_box.style.left = 0 + 'px';
//設置第一個小圖為當前按鈕 lis[0].className = 'cur'
//輪播切換 const swapImg =() =>{ img_box.style.left = -index * imgContainerW + 'px'; for (let i = 0; i < lis.length; i++) { lis[i].className = ''; } lis[index].className = 'cur' }
const swapFormat =() =>{ index++; if (index >= 4) { index = 4; img_box.style.transition = 'all, linear, 1s'; img_box.style.left = -index * imgContainerW + 'px'; for (let i = 0; i < lis.length; i++) { lis[i].className = ''; } lis[0].className = 'cur' //通過定時器立馬切換到第一張 setTimeout(()=>{ index = 0; img_box.style.transition = ''; swapImg(); }, 1500) } else { img_box.style.transition = 'all, linear, 1.5s'; swapImg(); } } // timer = setInterval(swapFormat, 3000)
//右按鈕 =>自動播放 right_btn.addEventListener('click', ()=>{ swapFormat(); })
//左按鈕 left_btn.addEventListener('click', () =>{ index--; if (index < 0) { index = -1 img_box.style.transition = 'all, linear, 1.5s'; img_box.style.left = -index * imgContainerW + 'px'; for (let i = 0; i < lis.length; i++) { lis[i].className = ''; } lis[3].className = 'cur'
setTimeout(()=>{ index = 3 img_box.style.transition = ''; swapImg(); }, 1000) } else { img_box.style.transition = 'all, linear, 1.5s'; swapImg(); } })
img_box.addEventListener('mouseover', () =>{ clearInterval(timer) })
right_btn.addEventListener('mouseover', () =>{ clearInterval(timer) })
left_btn.addEventListener('mouseover', () =>{ clearInterval(timer) })
img_box.addEventListener('mouseout', ()=> { timer = setInterval(swapFormat, 3000) })
left_btn.addEventListener('mouseout', ()=> { timer = setInterval(swapFormat, 3000) })
right_btn.addEventListener('mouseout', () =>{ timer = setInterval(swapFormat, 3000) })
|