圖示或按鈕在滑鼠移過時輕微抖動,是一種成本很低卻頗吸睛的回饋。原理並不玄妙:用 setTimeout 反覆微調元素的 left 與 top,讓它沿著上、右、下、左四個方向循環位移。
<STYLE>
.shakeimage {
POSITION: relative; /* 必須是 relative 或 absolute,left/top 才有效 */
}
</STYLE>
<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" onMouseOver="init(this); rattleimage()"
onMouseOut="stoprattle(this)" src="/images/csrcode.ico" border="0" style="cursor:pointer;" />
<img class="shakeimage" onmouseover="init(this); rattleimage()"
onmouseout="stoprattle(this)" src="/images/changshi.ico" border="0" style="cursor:pointer;" />
<img class="shakeimage" onmouseover="init(this); rattleimage()"
onmouseout="stoprattle(this)" src="/images/links.ico" border="0" style="cursor:pointer;" />
滑鼠滑過圖片預覽效果。
left 與 top 只在元素具有定位上下文時才生效。少了這行 CSS,腳本會照跑但畫面完全不動,是最常見的「跑不出效果」原因。
a 依序代表下、右、上、左,每次位移後加一,超過 4 就回到 1。四個方向連起來剛好是一個逆時針的小方圈,視覺上就是抖動。
移出時把 stopit 設為 1,下一輪 rattleimage 一進函式就 return,迴圈自然中止。這比用 clearInterval 簡單,因為原本用的是遞迴 setTimeout 而非 setInterval。
init 與 stoprattle 都把 left/top 設回 0,避免位移殘留導致圖片位置偏移。
第一,setTimeout("rattleimage()", 50) 用字串形式呼叫,等於再 eval 一次,應改成 setTimeout(rattleimage, 50)。第二,shake 是隱含的全域變數,多張圖同時互動時會互相干擾,應改用閉包或函式參數傳遞。第三,也是最重要的:這種持續位移的動畫對有前庭功能困擾的使用者可能造成不適,現行做法是用 CSS keyframes 一次搞定,並包在 prefers-reduced-motion 判斷裡:
@keyframes shake {
0%, 100% { transform: translate(0, 0); }
25% { transform: translate(0, 3px); }
50% { transform: translate(3px, 0); }
75% { transform: translate(0, -3px); }
}
.shakeimage:hover {
animation: shake .3s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.shakeimage:hover { animation: none; }
}
以 transform 動畫不觸發重排,效能明顯優於逐格改 left/top,程式碼也短得多。