想製作類似跑馬燈、讓文字持續滾動的效果嗎?本文示範如何封裝一個可重用、且能無縫循環的滾動元件,並支援左右移動與滑鼠移入暫停。
var moveTag = function(obj){
var _this = this;
_this.speed = 10; // 移動速度
_this.space = 10 * _this.speed; // 移動間隔時間
obj.scrollLeft = 0; // 初始化滾動位置(相容 FF)
var divList = obj.getElementsByTagName("DIV");
var obj2 = new Object();
for (var i = 0; i < divList.length; i++) {
if (divList[i].parentNode == obj) { obj2 = divList[i]; break; }
}
var cellCount = 0;
_this.cellList = new Array();
for (var i = 0; i < divList.length; i++) {
if (divList[i].parentNode == obj2) {
cellCount++;
_this.cellList.push(divList[i]);
}
}
// ...其餘 resetCellList、resetForMoveRight、move、start 等方法省略
_this.start = function(){ setInterval(_this.move, _this.speed); };
_this.moveRight = function(){ _this.scrollEnd = true; _this.isMoveLeft = false; _this.scrollTimes = 0; };
_this.moveLeft = function(){ _this.scrollEnd = false; _this.isMoveLeft = true; _this.scrollTimes = 0; };
};
#list{border:#ccc 1px solid;}
#list div div{line-height:30px;text-align:center;border-right:#ccc 1px solid;}
#list{width:150px;height:30px;overflow:hidden;}/* 必須:寬高可自訂 */
#list div div{width:150px;height:30px;float:left;}/* 必須:寬高最好與 #list 一致 */
<div id="list">
<div>
<div>第一列</div>
<div>第二列</div>
<div>第三列</div>
<div>第四列</div>
<div>第五列</div>
</div>
</div>
<a href="javascript:moveLeft()">左移動</a>
<a href="javascript:moveRight()">右移動</a>
<script>
var move = new moveTag(document.getElementById("list"));
move.start();
move.speed = 10; // 滾動速度,預設 10
var moveLeft = move.moveLeft;
var moveRight = move.moveRight;
</script>
這個元件的設計相當用心。它透過「把已滾過的列移到後方、把未到達的列移到前方」的方式(resetCellList 與 resetForMoveRight),讓滾動達到無縫循環、不會出現空白的斷層。同時還支援滑鼠移入暫停(moveStart 旗標)、左右反向移動,以及透過 speed 與 space 控制速度與間隔。作者特別提到,若同一頁想有多處滾動,只要多 new 幾個實例即可,互不干擾。這種以 scrollLeft 為核心、搭配 DOM 節點重排的封裝手法,是實作連續滾動時相當經典的思路。