DIV CSS 佈局教程網

用 onmouseover 與 onmouseout 做出圖片放大效果
編輯:關於JavaScript     

滑鼠移入時放大、移出時還原,是最經典的圖片互動效果。原理很單純:在兩個事件回呼裡分別改寫圖片的寬高。

 <!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>

傳入 this 的重要性

回呼函式接受一個參數 x,並由行內事件用 this 傳入。this 在行內 handlers 中指向觸發事件的元素本身,也就是那張 img。這樣同一組函式就能套用到頁面上任何圖片,不必為每張圖寫一份。

只改一邊會變形

寬高必須成比例放大,否則圖片會被拉歪。範例中 32→64 剛好是兩倍,所以沒問題。若尺寸不規則,較穩妥的做法是只放大一邊,讓另一邊自動等比例:

 function bigImg(x) {
   x.style.height = "64px";
   x.style.width = "auto";   // 讓寬度依原始比例自動計算
 }

改用 CSS 會更好

這類視覺效果交給 CSS 是更標準的做法,不僅程式碼更少,還能加上動畫:

 /* CSS */
.thumb { width: 32px; height: 32px; transition: width .2s, height .2s; }
.thumb:hover { width: 64px; height: 64px; }

/* JS 完全不需要 */

CSS 的 :hover 虛擬類別正是為此而生,而 transition 能讓放大過程平滑過渡——這是用 JS 直接改 style 無法(至少很難優雅)做到的。

transform 是更好的選擇

改 width/height 會觸發重排(reflow),也就是瀏覽器必須重新計算版面,圖片放大時還會把周圍元素推開,造成版面跳動。改用 transform 則只觸發合成(composite),效能好得多,而且不影響文件流:

 /* CSS */
.thumb { transition: transform .2s; }
.thumb:hover { transform: scale(2); }

若要讓放大後的圖疊在其他元素之上,再加 position: relative; z-index: 10; 即可。

順手補強

· 移除已棄用的 border="0" 屬性,改用 CSS border: none。
· 保留 alt 屬性,這是無障礙的基本要求。
· 建議改用 addEventListener 與 classList,避免行內事件與全域函式。
· 觸控裝置沒有 hover,這類效果在手机上不會出現,需另ways設計點擊行為。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved