跑馬燈式的水平滾動文字在公告欄、優惠訊息等場景仍很常見。與其用已廢棄的 <marquee> 標籤,不如自己封裝一個可控、可客製的元件。
<script type="text/javascript">
$(function(){
var setting = {
content : " @@@@@浮動文字#### ",
overStop : true,
width : "100px",
targetId : "huangbiao",
onAfterShow : function(obj){
obj.setting.width = "20px";
// 修改設定後可重新初始化
// obj.init();
// 或移除動態加入的節點
// obj.remove();
}
};
var ooo = new fontMove(setting);
});
</script>
整個效果建立在四層結構上:
1. 最外層 div 隱藏滾動條(overflow:hidden),它才是真正會捲動的容器。
2. 第二層 div 寬度設為 8000%,用來容納超寬內容。
3. 第三層有兩個子 div(div1 與 div2),內容完全相同,皆向左浮動並排。
4. 用計時器讓最外層的 scrollLeft 每次加 1;一旦捲動距離達到 div1 的寬度,就把 scrollLeft 減掉該寬度。
關鍵在於第 3 點的「內容複製兩份」。因為單一內容滾出視線左側後就消失了,若只有一份,畫面右側會出現空白。複製一份接在后面,就能在無縫銜接的情況下無限循環。
function fontMove(userSettingObj){
var that = this;
var timestamp = new Date().getTime(); // 用時間戳當唯一 id
this.setting = {
content : "浮動文字",
width : "200px",
speed : 30, // 每 30 毫秒移動一次
overStop : true, // 滑鼠移入是否暫停
objId : timestamp,
targetId : "", // 為空則放在 body 最後
onAfterShow : function(){ }
};
this.setting = $.extend(this.setting, userSettingObj);
this.callback = function(myfun){
if (typeof myfun == "function"){
myfun.call(that); // 這裡的 this 是 callback,需用 that 才指向實例
}
};
this.remove = function(){ $("#" + that.setting.objId).remove(); };
this.init = function(){
var domStr = '<div id="' + that.setting.objId + '" style="overflow:hidden;width:'
+ that.setting.width + '">'
+ '<div style="width:8000%;">'
+ '<div id="' + that.setting.objId + '_div1" style="float:left;">'
+ that.setting.content + '</div>'
+ '<div id="' + that.setting.objId + '_div2" style="float:left;">'
+ that.setting.content + '</div>'
+ '</div></div>';
if ("" == that.setting.targetId){
$("body").append(domStr);
} else {
$("#" + that.setting.targetId).html(domStr);
}
var thatDiv = document.getElementById(that.setting.objId);
var sonDiv1 = document.getElementById(that.setting.objId + '_div1');
this.Marquee = function(){
// scrollLeft 是可讀寫的,這正是整個效果的支點
if (thatDiv.scrollLeft - sonDiv1.offsetWidth >= 0){
// 已滾完一份內容,扣掉它的寬度回到起點,視覺上無縫
thatDiv.scrollLeft = thatDiv.scrollLeft - sonDiv1.offsetWidth;
} else {
thatDiv.scrollLeft++;
}
};
var myvar = setInterval(that.Marquee, that.setting.speed);
if (that.setting.overStop){
thatDiv.onmouseover = function(){ clearInterval(myvar); };
thatDiv.onmouseout = function(){ myvar = setInterval(Marquee, 30); };
}
if (typeof that.setting.onAfterShow == "function"){
that.setting.onAfterShow.call(that, that);
}
};
this.init();
return this; // 回傳自己,讓外部能存取所有設定
}
原始程式可以跑,但有幾處瑕疵值得在正式專案中修正:
一是 onmouseout 中的 setInterval(Marquee, 30) 少了 that.,Marquee 在該作用域下是未定義的變數,滑鼠移出後會拋出錯誤、動畫不會恢復。應改為 setInterval(that.Marquee, that.setting.speed),同時把 speed 硬編碼的 30 換成設定值。
二是把「單次移動量」也抽成設定(例如 step),比寫死 ++ 更有彈性,速度調整也更直觀。
三是頻繁操作 scrollLeft 會觸發重排,若追求效能可考慮改用 transform: translateX() 搭配 CSS transition,交由合成器處理,動畫會更順。
封裝元件時,「把可變項集中到 setting、用時間戳產生唯一 id、回傳 this 讓外部可調」這幾個習慣很值得沿用;再補上作用域與效能的修正,就是一個可靠的元件了。希望對你的 JavaScript 開發有所幫助。