圖片隨著滑鼠移入而切換、移開後恢復原樣,是很常見的互動效果。本文提供一個透過 onMouseOver 與 onMouseOut 事件切換圖片來源的做法。
<a href="#">
<img src="red.gif" border="0"
onMouseOver="this.src='blue.gif'"
onMouseOut="this.src='green.gif'" />
</a>
在迴圈或動態拼接的場景中,要注意引號的轉義:
<img src="images/red'+i+'s.png" style="width:20px;height:29px;"
onMouseOver="this.src=\'images/blue'+i+'s.png\'"
onMouseOut="this.src=\'images/red'+i+'s.png\'">
初始狀態:
滑鼠移入:
滑鼠移開:
這個做法簡單直觀,適合靜態或少量圖片的場景。若要處理大量圖片,建議改用 CSS 精靈圖搭配 :hover,能減少 HTTP 請求、提升效能。