透過擴展 jQuery.fn.shake,讓任何 jQuery 物件獲得抖動能力。原理:在相對定位下,交替向左、向右位移指定距離,重複指定次數,形成水平抖動。
jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
this.each(function() {
var $node = $(this);
$node.css({ position: 'relative' });
for (var x = 1; x <= intShakes; x++) {
$node.animate({ left: -intDistance }, ((intDuration / intShakes) / 4))
.animate({ left: intDistance }, ((intDuration / intShakes) / 2))
.animate({ left: 0 }, ((intDuration / intShakes) / 4));
}
});
return this; // 支援鏈式呼叫
};
$(function() {
$('#btn').click(function() {
$(this).shake(2, 10, 400); // 抖動 2 次,位移 10px,總時長 400ms
});
});
| 參數 | 說明 |
|---|---|
intShakes | 抖動週期數(來回算一次) |
intDistance | 單次位移像素 |
intDuration | 總持續毫秒數 |
.stop(true) 清除佇列。direction 參數支援垂直抖動(top)。@keyframes shake 配合 animation 類別切換更高效,不佔用 JS 執行緒。@keyframes shake {
0%, 100% { transform: translateX(0); }
20% { transform: translateX(-10px); }
40% { transform: translateX(10px); }
60% { transform: translateX(-10px); }
80% { transform: translateX(10px); }
}
.shake { animation: shake 0.4s; }
JS 僅需 $(el).addClass('shake').one('animationend', () => $(el).removeClass('shake')); 即可觸發一次抖動。