這裡分享一個自己寫的跑馬燈小程序。它把滾動邏輯封裝成一個構造函數,透過傳入容器 id、內容 id 與速度參數來初始化,接口相對清晰。
function cls_marquee(id, id1, id2, sp){
this.obj_id = id;
this.obj_id1 = id1;
this.obj_id2 = id2;
this.speed = sp;
eval(this.obj_id2 + ".innerHTML=" + this.obj_id1 + ".innerHTML");
function Marquee(){
if(eval(id2).offsetTop - eval(id).scrollTop <= 0)
eval(id).scrollTop -= eval(id1).offsetHeight;
else{
eval(id).scrollTop++;
}
}
var MyMar = setInterval(Marquee, sp);
eval(this.obj_id).onmouseover = function() { clearInterval(MyMar); };
eval(this.obj_id).onmouseout = function() { MyMar = setInterval(Marquee, sp); };
}
它的原理與前面介紹的滾動一致:把內容複製一份接到後面,滾動到頭時瞬間跳回,並在滑鼠移入時暫停、移出時繼續。
另外再附上一個用輸入框實現文字滾動的小例子,一個向左滾、一個向右滾:
<script type="text/javascript">
function show() {
var info = document.getElementById('Text1');
info.value = info.value.substr(1) + info.value[0];
}
setInterval(show, 500);
function show1() {
var info1 = document.getElementById('Text2');
info1.value = info1.value[info1.value.length-1] + info1.value.substr(0, info1.value.length-1);
}
setInterval(show1, 500);
</script>
<input id="Text1" type="text" value="歡迎來測試" />
<input id="Button1" type="button" value="滾動"/><br />
<input id="Text2" type="text" value="北京歡迎您" />
<input id="Button2" type="button" value="滾動" onclick="show1()" />
這裡的巧思在於利用字串的 substr 與首尾拼接:把第一個字符移到末尾就實現了左滾,把最後一個字符移到開頭則實現了右滾。