萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現層抖動特效:模仿 WordPress 登錄失敗搖晃動畫

效果預覽

點擊元素觸發水平左右快速位移動畫,模仿 WordPress 後台登錄錯誤時的輸入框抖動提示。

核心實現:鏈式 animate 疊加位移

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 相對當前位置移動,無需計算絕對坐標。
  • 動畫隊列:jQuery animate() 默認進入 fx 隊列依次執行,實現連續抖動。
  • 極短時長:每段 3ms,總體約 72ms (6輪×4段×3ms),產生「瞬間抖動」視覺感。
  • 歸位:最後動畫回到初始 box_left,確保不偏移。

優化版:使用 CSS 動畫 + JS 觸發(推薦)

.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 微調曲線與時長。

適用場景

  • 表單驗證失敗提示
  • 按鈕點擊無效反饋
  • 重要通知吸引注意
避免濫用:頻繁或大面積抖動會干擾用戶體驗,僅在關鍵錯誤提示時使用。
copyright © 萬盛學電腦網 all rights reserved