在網頁中,常會希望滑鼠移入表格或列時,背景能有所變化,以提升可讀性與互動感。這種效果可以透過 onmouseover 與 onmouseout 完成。
如果希望滑鼠移入時換成另一張圖,可以準備兩張圖片,並在事件處理中切換背景。
<table onmouseover="this.style.backgroundImage='url(images/jb51-1.jpg)'" onmouseout="this.style.backgroundImage='url(images/jb51-2.jpg)'"> </table>
如果只是要改變顏色,可以直接操作 backgroundColor。
<tr onmouseover="this.style.backgroundColor='#E0E0E0'" onmouseout="this.style.backgroundColor='#FFFFFF'"> </tr>
傳統寫法有時會使用 bgColor 屬性,但較建議使用 style.backgroundColor,因為它更符合標準,也更容易與 CSS 搭配。若效果較多,也可以改用 CSS 的:hover,讓樣式與 JavaScript 分離。