今天學(xué)習(xí)了一個(gè)js實(shí)現(xiàn)圖片的無縫輪播滾動(dòng)來和打攪分享一下
大體效果如上圖所示:就是4張圖片一直在兩個(gè)按鈕之間來回滾動(dòng)下面介紹一個(gè)實(shí)現(xiàn)原理毡们。
實(shí)現(xiàn)4張圖片在兩個(gè)按鈕之間來回滾動(dòng)假設(shè)先向左滾動(dòng)首先我們通過 oUl.innerHTML+=oUl.innerHTML; 使里面的長(zhǎng)度加一倍這樣保證能在第四幅圖片出來后第一副圖片也能接著出來。接下來就是要讓他循環(huán)顯示:這里要用到一個(gè)屬性:oUl.offsetWidth ul的寬度當(dāng)?shù)谒姆鶊D片剛好滾出屏幕時(shí)岂昭,此時(shí)畫面的顯示效果和初始狀態(tài)一模一樣,我們讓他回到初始狀態(tài)即可
l-=g_iSpeed; if(l<=-oUl.offsetWidth/2) { l+=oUl.offsetWidth/2; }
l記錄滾動(dòng)長(zhǎng)度 當(dāng)?shù)谒姆鶊D片剛好滾出屏幕時(shí) 此時(shí)l的數(shù)值剛好為總長(zhǎng)的一半 我們讓他加上一般回歸到初始狀態(tài)
向右同理js代碼中有不再詳細(xì)敘述
http://mp.weixin.qq.com/s/EIv2DvRExr0QqUej8hgH7w
css樣式:
{padding:0;margin:0;}li{list-style: none}img{border: 0}.roll{width:698px; height:108px; margin:50px auto 0;position: relative; }.btn_left{display: block;width: 68px; height: 68px;background: url(images/btn.jpg) no-repeat -70px -69px;position: absolute; top:20px;left: 1px;z-index: 1;}.btn_left:hover { background: url(images/btn.jpg) no-repeat -70px 0; }.btn_right { display: block; width: 68px; height: 68px; background: url(images/btn.jpg) no-repeat 1px -69px; position: absolute; top: 20px; right: 0; z-index: 1; }.btn_right:hover { background: url(images/btn.jpg) no-repeat 1px 0; }.roll .wrap{width:546px; height:108px; margin:0 auto; position:relative; overflow: hidden;}.roll ul { position: absolute; top: 0; left: 0; }.roll li { float: left; width: 182px; height: 108px; text-align: center; }.roll li a:hover { position: relative; top: 2px; }.control { border-bottom: 1px solid #ccc; background: #eee; text-align: center; padding: 20px 0; display: none; }
js:
var g_bMoveLeft=true;var g_oTimer=null;var g_iSpeed=3;window.onload=function(){ var oDiv=document.getElementById('roll'); var oUl=oDiv.getElementsByTagName('ul')[0]; var aLi=oUl.getElementsByTagName('li'); var aA=oDiv.getElementsByTagName('a'); oUl.innerHTML+=oUl.innerHTML; oUl.style.width=aLi[0].offsetWidthaLi.length+'px'; for (var i = 0; i <aLi.length; i++) { aLi[i].onmouseover=function(){ stopMove(); } aLi[i].onmouseout=function(){ startMove(g_bMoveLeft); } } aA[0].onmouseover=function () { startMove(true); }; aA[1].onmouseover=function () { startMove(false); }; startMove(true);};function startMove(bLeft){ g_bMoveLeft=bLeft; if(g_oTimer) { clearInterval(g_oTimer); } g_oTimer=setInterval(doMove, 30);}function stopMove(){ clearInterval(g_oTimer); g_oTimer=null;}function doMove(){ var oDiv=document.getElementById('roll'); var oUl=oDiv.getElementsByTagName('ul')[0]; var aLi=oUl.getElementsByTagName('li'); var l=oUl.offsetLeft; if(g_bMoveLeft) { l-=g_iSpeed; if(l<=-oUl.offsetWidth/2) { l+=oUl.offsetWidth/2; } } else { l+=g_iSpeed; if(l>=0) { l-=oUl.offsetWidth/2; } } oUl.style.left=l+'px';}