想讓文字在頁面上左右滾動,有兩種常見做法。
<MARQUEE behavior="scroll" contenteditable="true" onstart="this.firstChild.innerHTML+=this.firstChild.innerHTML;" scrollamount="3" width="100"> <SPAN unselectable="on">這裡是要滾動的內容</SPAN> </MARQUEE>
<DIV id="scrollobj" style="white-space:nowrap;overflow:hidden;width:500px;">
<span>這裡是要滾動的內容</span>
</DIV>
<script 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;
}
setInterval("scroll(document.getElementById('scrollobj'))",20);
</script>
marquee 寫法最為簡潔,而 JS 寫法則透過 setInterval 定時遞增 scrollLeft,並在內容滾完時複製一倍的內容、滾過初始寬度時歸零,達到無縫循環的效果。