<marquee> 做起跑馬燈很省事,但它只在 IE 有效,而且早已被標準淘汰。下面示範兩種寫法:先看上不了檯面的舊做法,再看跨瀏覽器的 div 版本。
複製代碼 代碼如下:
<marquee behavior="scroll" contenteditable="true" onstart="this.firstChild.innerHTML+=this.firstChild.innerHTML;" scrollamount="3" width="100" onmouseover="this.stop();" onmouseout="this.start();"> 這裡是要滾動的內容 </marquee>
它的「無縫」技巧是在啟動時把內容複製一份接在自己後面,滾到一半剛好接上複製的那份,視覺上看不出斷點。
複製代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>div+css+javascript 實現無縫滾動,兼容 firefox</title>
<style type="text/css">
#scrollobj {
white-space: nowrap;
overflow: hidden;
width: 500px;
}
</style>
</head>
<body>
<div id="scrollobj" onmouseover="javascript:_stop();" onmouseout="javascript:_start();">
這裡是要滾動的內容
</div>
<script language="javascript" type="text/javascript">
<!--
function scroll(obj) {
/*往左*/
var tmp = (obj.scrollLeft)++;
//當滾動條到達右邊頂端時
if (obj.scrollLeft == tmp) {
obj.innerHTML += obj.innerHTML;
}
//當滾動條滾動了初始內容的寬度時滾動條回到最左端
if (obj.scrollLeft >= obj.firstChild.offsetWidth) {
obj.scrollLeft = 0;
}
/*往上*/
//var tmp = (obj.scrollTop)++;
//if (obj.scrollTop == tmp) {
// obj.innerHTML += obj.innerHTML;
//}
//if (obj.scrollTop >= obj.firstChild.offsetWidth) {
// obj.scrollTop = 0;
//}
}
var _timer = setInterval("scroll(document.getElementById('scrollobj'))", 20);
function _stop() {
if (_timer != null) {
clearInterval(_timer);
}
}
function _start() {
_timer = setInterval("scroll(document.getElementById('scrollobj'))", 20);
}
//-->
</script>
</body>
</html>
容器的 CSS 是關鍵:white-space:nowrap 讓內容不換行,overflow:hidden 把溢出部分藏起來。JS 每 20 毫秒把 scrollLeft 加一,一旦滾到「已經看不見」的位置(scrollLeft 無法再增加,或達到首段內容的寬度)就把 scrollLeft 歸零,視覺上就銜接回去了。註解中的 scrollTop 版本是同一套邏輯改成垂直方向滾動。
三個可以改良的地方:一是 setInterval 的字串寫法應該改成直接傳函式參照,效能與可讀性都更好;二是歸零前若沒有先把內容複製一份,會出現一段空白,實作時記得在載入後執行 obj.innerHTML += obj.innerHTML;三是滑鼠移入停止/移出繼續的設計很好,記得頁面卸載時清掉計時器,避免殘留。