利用 position: relative 讓圖片可定位,配合 setTimeout 循環修改 style.left、style.top,形成上下左右抖動 4 方向的震動動畫。滑鼠移入啟動,移出停止並歸位。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>滑鼠滑過 圖片震動效果</title>
<style>
.shakeimage { position: relative; }
</style>
</head>
<body>
<script language="JavaScript1.2">
//<![CDATA[
var rector = 3; // 震動位移像素
var stopit = 0; // 停止旗標
var a = 1; // 方向計數 1~4
var shake; // 當前震動元素
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;
switch (a) {
case 1: shake.style.top = parseInt(shake.style.top) + rector; break;
case 2: shake.style.left = parseInt(shake.style.left) + rector; break;
case 3: shake.style.top = parseInt(shake.style.top) - rector; break;
case 4: shake.style.left = parseInt(shake.style.left) - rector; break;
}
a = (a < 4) ? a + 1 : 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;" />
<p>滑鼠滑過圖片預覽效果。</p>
</body>
</html>
rector 控制每步位移量,越大震動幅度越明顯。setTimeout 遞迴呼叫自身,約 20fps(50ms/幀)。stopit=1 並重置座標,停止動畫。純 CSS 即可實現更流暢、效能更好的震動效果,無需 JavaScript 計時器:
@keyframes shake {
0%, 100% { transform: translate(0,0); }
25% { transform: translate(3px, 0); }
50% { transform: translate(0, 3px); }
75% { transform: translate(-3px, 0); }
}
.shakeimage:hover { animation: shake 0.2s infinite; }
優點:GPU 加速、不阻塞主執行緒、程式碼極簡。