點擊元素觸發水平左右快速位移動畫,模仿 WordPress 後台登錄錯誤時的輸入框抖動提示。
var box_left = 0;
$(function() {
// 初始化居中位置
box_left = ($(window).width() - $('#box').width()) / 2;
$('#box, #footer').css({ left: box_left, position: 'absolute' });
});
function shock() {
for (var i = 1; i < 7; i++) {
$('#box').animate({ left: '-=15' }, 3)
.animate({ left: '+=30' }, 3)
.animate({ left: '-=15' }, 3)
.animate({ left: box_left }, 3);
}
}
-=15、+=30 相對當前位置移動,無需計算絕對坐標。animate() 默認進入 fx 隊列依次執行,實現連續抖動。box_left,確保不偏移。.shake {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
transform: translate3d(0, 0, 0); /* 啟用 GPU 加速 */
}
@keyframes shake {
10%, 90% { transform: translate3d(-1px, 0, 0); }
20%, 80% { transform: translate3d(2px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
40%, 60% { transform: translate3d(4px, 0, 0); }
}
// JS 觸發
function shakeElement($el) {
$el.addClass('shake').one('animationend', function() {
$(this).removeClass('shake');
});
}
優點:性能更好(GPU 加速)、代碼解耦、易維護、可通過 CSS 微調曲線與時長。
避免濫用:頻繁或大面積抖動會干擾用戶體驗,僅在關鍵錯誤提示時使用。