marquee 是實現簡單滑動效果最省事的元素,一個標籤就能讓文字或圖片動起來。
<style type="text/css">
#div01{ width: 500px; }
</style>
<marquee behavior="alternate"><font size="30" color="red">www.example.com111</font></marquee>
<marquee direction="right" bgcolor="#ff2233" behavior="alternate">
<font size="30" color="blue">www.example.com222</font>
</marquee>
<marquee id="m3" direction="down" bgcolor="#dbdbdb" height="50px"
hspace="20px" vspace="20px" behavior="alternate"
onmouseover="this.stop()" onmouseout="this.start()">
<font size="30" color="blue">www.example333.com</font>
</marquee>
<marquee id="m4" direction="up" bgcolor="#00dbdb" behavior="alternate">
<font size="30" color="blue">www.example444.com</font>
</marquee>
<div id="div01">
<marquee direction="right" bgcolor="#ff2233" behavior="alternate" scrolldelay="100">
<font size="30" color="blue">www.example.com555</font>
</marquee>
</div>
<input type="button" onclick="m3.stop();" value="m3.stop">
<input type="button" onclick="m3.start();" value="m3.start">
<button onclick="m4.stop();">m4.stop</button>
<button onclick="m4.start();">m4.start</button>
坦白說,marquee 與 <font> 一樣屬於已棄用的元素,HTML5 標準中並不存在,behavior、bgcolor 這類屬性也不再建議使用。它能跑,多半是因為瀏覽器基於相容性仍保留實作。
新專案若要同樣的效果,建議改用 CSS 動畫:
.ticker{
overflow: hidden;
white-space: nowrap;
}
.ticker span{
display: inline-block;
padding-left: 100%;
animation: marquee 15s linear infinite;
}
@keyframes marquee{
to{ transform: translateX(-100%); }
}
.ticker:hover span{ animation-play-state: paused; }
好處很明確:效能更好(走合成層而非重排)、樣式完全可控、hover 暫停只需一行,而且符合無障礙規範。另外記得尊重 prefers-reduced-motion 偏好,為停用動效的使用者關掉滾動。