滑鼠移上去,圖標像被電了一樣左右上下抖動;移開立刻歸位。這個效果的原理單純得令人愉悅:讓元素依「下、右、上、左」四個方向輪流位移。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>滑鼠滑過 圖片震動效果</title>
<style>
.shakeimage { POSITION: relative; } /* 必須是非 static,top/left 才有效 */
</style>
</head>
<body>
<script language="JavaScript1.2">
<!--
var rector = 3; // 每次位移的像素數
var stopit = 0; // 停止旗標
var a = 1; // 目前方向:1下 2右 3上 4左
function init(which) {
stopit = 0;
shake = which;
shake.style.left = 0;
shake.style.top = 0;
}
function rattleimage() {
if ((!document.all && !document.getElementById) || stopit == 1) return;
if (a == 1) shake.style.top = parseInt(shake.style.top) + rector;
else if (a == 2) shake.style.left = parseInt(shake.style.left) + rector;
else if (a == 3) shake.style.top = parseInt(shake.style.top) - rector;
else shake.style.left = parseInt(shake.style.left) - rector;
if (a < 4) a++; else a = 1; // 循環四個方向
setTimeout("rattleimage()", 50);
}
function stoprattle(which) {
stopit = 1;
which.style.left = 0;
which.style.top = 0;
}
//-->
</script>
<img class="shakeimage" src="/images/csrcode.ico" border="0" style="cursor:pointer;"
onMouseOver="init(this);rattleimage()"
onMouseOut="stoprattle(this)">
<img class="shakeimage" src="/images/changshi.ico" border="0" style="cursor:pointer;"
onmouseover="init(this);rattleimage()"
onmouseout="stoprattle(this)">
<img class="shakeimage" src="/images/links.ico" border="0" style="cursor:pointer;"
onmouseover="init(this);rattleimage()"
onmouseout="stoprattle(this)">
滑鼠滑過圖片預覽效果。
</body>
</html>
關鍵是變數 a 的四段循環:
a=1:top 加 3(往下)a=2:left 加 3(往右)a=3:top 減 3(往上)a=4:left 減 3(往左)每 50ms 換一次方向,元素就沿著一個小正方形邊界繞圈,看起來就是高頻抖動。振幅由 rector 決定,頻率由 setTimeout 的延時決定。
另外注意 CSS 裡的 position: relative 是必須的——只有非 static 定位的元素,top 與 left 才會生效。這是很多初學者漏掉的一步。
1. shake 是全域變數。三張圖片共用同一個 shake,若快速在多張圖間移動,會互相干擾(圖片抖到一半換成抖另一張)。應該改用參數傳遞或閉包封裝每個實例。
2. 計時器沒有保存 id。setTimeout 的返回值沒被記錄,所以無法 clearTimeout,只能靠 stopit 旗標讓下一次回呼自行 return。這樣在停止後仍會有一次多餘的排程。正確做法是把 id 存起來並確實清除。
3. parseInt 缺少基數參數。寫成 parseInt(x, 10) 較安全。
4. 位移未加單位。標準模式下 style.top = 3 是無效的,必須寫 '3px'。
震動本質是關鍵帧動畫,用 CSS 表達最合適,而且完全不需要 JS:
<style>
@keyframes shake {
0%, 100% { transform: translate(0, 0); }
25% { transform: translate(0, 3px); }
50% { transform: translate(3px, 0); }
75% { transform: translate(0, -3px); }
}
.shakeimage { position: relative; }
.shakeimage:hover, .shakeimage:focus {
animation: shake .2s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.shakeimage:hover { animation: none; } /* 尊重使用者偏好 */
}
</style>
用 transform 而非 top/left 的好處是只觸發合成、不重排,動畫會順很多。
持續震動的視覺刺激很容易讓人分心,對有前庭功能敏感或注意力障礙的使用者尤其不友善——這正是 prefers-reduced-motion 存在的理由。實務上建議:只用於短暫的一次性回饋(例如「複製成功」的確認),而不是長時間持續播放;互動目標若是重要功能按鈕,請確認震動不會造成點擊落空;並為圖片加上有意義的 alt 文字。