QQ 最經典的互動之一,就是「抖動視窗」——收到對方抖動時,整個對話框會左右快速晃動。原理其實很單純:用 setTimeout 連續小幅位移元素的座標,營造出震動的錯覺。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript 層抖動效果</title>
<style type="text/css">
#body { text-align: center; }
#test {
width: 200px;
position: absolute;
margin: 10px auto;
height: 100px;
border: 2px dotted red;
text-align: center;
}
</style>
</head>
<body>
<div style="margin: 10px 200px">
<div>
<input type="button" value="~點這裡讓我抖抖吧~" onclick="nn.start()" />
</div>
<div>
<input type="button" value="晃暈了,我不抖了!" onclick="nn.stop()" />
</div>
<div id="test">
<br>
<img border="0" src="smiley.gif">
</div>
</div>
<script type="text/javascript">
var m = document.getElementById("test");
function SKclass(obj, Rate, speed) {
var oL = obj.offsetLeft;
var oT = obj.offsetTop;
this.stop = null;
this.oTime = null;
var om = this;
this.start = function () {
if (parseInt(obj.style.left) == oL - 2) {
obj.style.top = oT + 2 + "px";
setTimeout(function () { obj.style.left = oL + 2 + "px"; }, Rate);
} else {
obj.style.top = oT - 2 + "px";
setTimeout(function () { obj.style.left = oL - 2 + "px"; }, Rate);
}
this.oTime = setTimeout(function () { om.start(); }, speed);
};
this.stop = function () {
clearTimeout(this.oTime);
};
}
var nn = new SKclass(m, 20, 70);
</script>
</body>
</html>
<img id="win" style="position:relative" src="smiley.gif">
<br /><br />
<button onclick="zd()">振動</button>
<script>
function zd(u) {
var a = ['top', 'left'], b = 0;
u = setInterval(function () {
document.getElementById('win').style[a[b % 2]] = (b++) % 4 < 2 ? 0 : 4;
if (b > 15) { clearInterval(u); b = 0; }
}, 32);
}
</script>
這版用陣列 ['top','left'] 輪流切換要動的軸向,再用取模運算決定位移量,總共跳動 15 次後自動停止,程式碼短得多。
用 JavaScript 逐格改 top/left 會不斷觸發重排,效能不理想。今天更好的方式是定義一段 CSS 動畫,JavaScript 只負責加上 class:
@keyframes shake {
0%, 100% { transform: translateX(0); }
20% { transform: translateX(-6px); }
40% { transform: translateX(6px); }
60% { transform: translateX(-4px); }
80% { transform: translateX(4px); }
}
.shake {
animation: shake 0.5s ease-in-out;
}
var win = document.getElementById('win');
function shake(el) {
el.classList.remove('shake');
void el.offsetWidth; // 強制重排,讓動畫可以重複觸發
el.classList.add('shake');
}
transform 屬於合成器屬性,動畫由 GPU 處理,不會引起版面重排,效果比位移 top/left 順得多。若想支援連續抖動,可把 animation-iteration-count 設為 infinite,再用 classList.remove('shake') 停止。
另外提醒:抖動這類高頻視覺刺激可能讓部分使用者不適,建議加上 @media (prefers-reduced-motion: reduce) 提供關閉選項。