DIV CSS 佈局教程網

手寫簡單易懂的無縫捲動 JavaScript 特效
編輯:關於JavaScript     

無縫捲動的原理

無縫捲動(跑馬燈)的技巧其實不複雜:先把內容複製一份接在後面,讓總寬度變成兩倍,接著讓元素持續向左移動;當移動距離達到「原本內容的寬度」時,就把位置瞬間歸零。由於後面緊接著一模一樣的內容,視覺上看起來就像永無止境地循環,銜接處毫無破綻。

完整程式碼

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<style>
*{padding:0; margin:0;}
ul{ list-style:none;}
#div{ width:300px; height:100px; margin:100px auto; border:1px solid #ff0000; position:relative; overflow:hidden;}
#div ul{ position:absolute; height:100px; left:0;}
#div ul li{ width:300px; height:100px; line-height:100px; text-align:center; float:left}
</style>
<script>
window.onload=function(){
    var oDiv=document.getElementById("div");
    var oUl=oDiv.getElementsByTagName("ul")[0];
    var oLi=oUl.getElementsByTagName("li");
    var oInput=document.getElementsByTagName('input');
    oUl.innerHTML += oUl.innerHTML;               // 複製一份內容
    oUl.style.width=oLi[0].offsetWidth*oLi.length+"px";
    var iSeep=-2;
    var tamer=null;
    clearInterval(tamer);
    function starMove(){
        tamer=setInterval(function(){
            oUl.style.left=oUl.offsetLeft+iSeep+"px";
            if(-oUl.offsetLeft >= oUl.offsetWidth/2){
                oUl.style.left="0px";
            }else if(oUl.offsetLeft>0){
                oUl.style.left=-oUl.offsetWidth/2+"px";
            }
        },30)
    }
    starMove();
    oDiv.onmouseover=function(){
        clearInterval(tamer);                     // 滑入暫停
    }
    oDiv.onmouseout=function(){
        starMove();                               // 滑出恢復
    }
    oInput[0].onclick=function(){
        iSeep=-2;                                 // 向左
    }
    oInput[1].onclick=function(){
        iSeep=2;                                  // 向右
    }
}
</script>
</head>
<body>
<input type="button" value="左">
<input type="button" value="右">
<div id='div'>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
</body>
</html>

重點說明

程式透過 oUl.innerHTML += oUl.innerHTML 把內容複製一份,再以 setInterval 每 30 毫秒移動一次。判斷條件 -oUl.offsetLeft >= oUl.offsetWidth/2 用來偵測是否已捲動到「一半寬度」(也就是原始內容的長度),若是就歸零。此外也示範了滑鼠移入暫停、移出恢復,以及用左右按鈕切換捲動方向的互動效果,讓這個小特效更完整實用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved