本文示範一個常見的小互動:滑鼠移入圖片時自動放大,移出後還原。
做法是分別綁定 onmouseover 與 onmouseout,在各自的處理函式中改寫圖片的寬高。
<!DOCTYPE html> <html> <head> <script> function bigImg(x) { x.style.height="64px"; x.style.width="64px"; } function normalImg(x) { x.style.height="32px"; x.style.width="32px"; } </script> </head> <body> <img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32"> <p>The function bigImg() is triggered when the user moves the mouse pointer over the image.</p> <p>The function normalImg() is triggered when the mouse pointer is moved out of the image.</p> </body> </html>
這裡有個關鍵技巧:處理函式接收一個參數 x,並以 this 傳入,這樣同一組函式就能套用到頁面上任何圖片,不必為每張圖各寫一份。
不過要注意一個實務問題:直接放大 width/height 會擠壓版面,造成周圍元素跳動。若想避免這種「推擠感」,建議改用 transform: scale(1.5) 並搭配 transition,因為 transform 不參與版面計算,動畫也更平順。另外,行動裝置沒有 hover 概念,這類效果在觸控環境下應考慮關閉或改為點擊觸發。
希望本文所述對大家的 JavaScript 程式設計有所幫助。