這份程式碼最大的優點是「複製貼上幾乎不用改就能跑」。它把捲動邏輯封裝成兩個函式——scrollSP 負責水平方向、scrollSZ 負責垂直方向——並自動處理邊界、滑鼠暫停等細節,非常適合直接嵌入專案。
function scrollSZ(con_id,speed,direct){
var con,items,heightHalf,heightAll;
var timer;
speed = parseInt(speed); // 獲取設置的速度參數
con = document.getElementById(con_id);
con.style.overflow = "hidden";
if(direct == "top"){ direct = "top"; }
else if(direct == "bottom"){ direct = "bottom"; }
else{ direct = "top"; }
con.innerHTML += con.innerHTML; // 複製內容
con.innerHTML += con.innerHTML;
items = getChildNodes(con);
if(items.length < 1){ return; }
heightAll = 0;
for(var i=0;i<items.length;i++){
var numTop,numBottom;
if (!!window.ActiveXObject){
numTop = items[i].currentStyle["marginTop"];
numBottom = items[i].currentStyle["marginBottom"];
}else{
numTop = document.defaultView.getComputedStyle(items[i],null)["marginTop"];
numBottom = document.defaultView.getComputedStyle(items[i],null)["marginBottom"];
}
numTop = parseInt(numTop);
numBottom = parseInt(numBottom);
numTop += numBottom;
if(numTop > 0){ heightAll += numTop; }
heightAll += items[i].offsetHeight;
}
heightHalf = heightAll/2;
if(direct == "bottom"){
con.scrollTop = heightHalf;
timer = setInterval(_scrollBottom,speed);
}else if(direct == "top"){
timer = setInterval(_scrollTop,speed);
}
con.onmouseover = function(){
if(timer){ clearInterval(timer); timer = null; }
};
con.onmouseout = function(){
if(!timer){
if(direct == "top"){ timer = setInterval(_scrollTop,speed); }
else if(direct == "bottom"){ timer = setInterval(_scrollBottom,speed); }
}
};
function _scrollTop(){
if(con.scrollTop < heightHalf){ con.scrollTop += 2; }
else{ con.scrollTop = 0; }
}
function _scrollBottom(){
if(con.scrollTop > 0){ con.scrollTop -= 2; }
else{ con.scrollTop = heightHalf; }
}
}
水平方向的 scrollSP 結構類似,只是改用 scrollLeft 並把子元素設為浮動排列,同時透過 getChildNodes 過濾出真正的元素節點(排除文字節點):
function getChildNodes(obj){ // 獲取元素子節點
var childList,list;
childList = new Array();
list = obj.childNodes;
for(var i=0;i<list.length;i++){
if(list[i].nodeType == 1)
childList[childList.length] = list[i];
}
return childList;
}
<script language="javascript">scrollSP("left_1",10,"right");</script>
這組函式貼心地處理了幾個實務細節:一是同時兼容 IE 的 currentStyle 與標準瀏覽器的 getComputedStyle 來取得邊距;二是把內容複製多份並計算「一半高度/寬度」作為歸零依據,確保循環無縫;三是滑鼠移入暫停、移出恢復。只要傳入容器 id、速度與方向,就能立刻得到一段順暢的捲動效果。