學(xué)習(xí)前端也有一小段時(shí)間了,當(dāng)初在學(xué)習(xí)javascript的時(shí)候,練手的一個(gè)輪播圖實(shí)例,輪播圖也是挺常見(jiàn)的了。
著是通過(guò)獲取圖片偏移量實(shí)現(xiàn)的,也實(shí)現(xiàn)了無(wú)縫切換,還有一點(diǎn)問(wèn)題就是沒(méi)有加上圖片切換的時(shí)候的延遲了。
html:
<div id="container"> <div id="list" style="left: -600px;"> <img src="../image/1.jpg" alt="5"> <img src="../image/1.jpg" alt="1"> <img src="../image/2.jpg" alt="2"> <img src="../image/3.jpg" alt="3"> <img src="../image/4.jpg" alt="4"> <img src="../image/5.jpg" alt="5"> <img src="../image/1.jpg" alt="1"> </div> <div id="buttons"> <span class="on"></span> <span></span> <span></span> <span></span> <span></span> </div> <a href="javascript:;" id="prev" class="arrow"><</a> <a href="javascript:;" id="next" class="arrow">></a> </div>
js:
window.onload = function(){ //獲取元素 var container = document.getElementById('container'); var list = this.document.getElementById('list'); var buttons = document.getElementById('buttons').getElementsByTagName('span'); var prev = document.getElementById('prev'); var next = document.getElementById('next'); var index = 1;//默認(rèn)第一個(gè)小圓點(diǎn)亮 //小圓點(diǎn)的點(diǎn)亮 function showButton() { //遍歷小圓點(diǎn)的個(gè)數(shù),當(dāng)觸發(fā)onclick事件后,className為‘on'的變?yōu)椤?。 for(var i = 0;i < buttons.length; i++){ if(buttons[i].className == 'on'){ buttons[i].className = ''; break; } } buttons[index - 1].className = 'on'; //原始第一個(gè)小圓點(diǎn)點(diǎn)亮,onclick事件觸發(fā)后,index+1 } function animate (offset) { //獲取從第一張圖片開(kāi)始發(fā)生的偏移量 var newLift = parseInt(list.style.left) + offset; list.style.left = newLift + 'px'; if(newLift > -600){ //如果偏移量的位置大于-600的時(shí)候,圖片跳轉(zhuǎn)到第五張圖片 list.style.left = -3000 + 'px'; } if(newLift < -3000){ //如果偏移量的位置大于-3000的時(shí)候,圖片跳轉(zhuǎn)到第一張圖片 list.style.left = -600 + 'px'; } } next.onclick = function () { //如果button的index為5的時(shí)候,再點(diǎn)擊next按鈕會(huì)返回 1; if(index == 5){ index = 1; }else{ index += 1; } showButton(); animate(-600); } prev.onclick = function () { if(index == 1){ index = 5; }else{ index -= 1; } showButton(); animate(600); } }
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com