不少網站(如早期的 WordPress 後台)在登入失敗時,會讓登入框左右晃動一下,用這種帶點俏皮的方式提示使用者輸入有誤。這個效果可以用 jQuery 的 animate() 來模擬。
原理很直觀:讓元素先向左移動一點、再向右、再回到原位,重複幾次並在最後復位,就形成了「晃動」的視覺感受。以下是核心函式:
var box_left = 0;
$(document).ready(function () {
// 計算水平置中位置
box_left = ($(window).width() - $('#box').width()) / 2;
$('#box,#footer').css({ 'left': box_left, 'position': 'absolute' });
});
function shock() {
for (i = 1; i < 7; i++) {
$('#box').animate({ 'left': '-=15' }, 3, function() {
$(this).animate({ 'left': '+=30' }, 3, function() {
$(this).animate({ 'left': '-=15' }, 3, function() {
$(this).animate({ 'left': box_left }, 3, function() {
// 晃動結束
});
});
});
});
}
}
透過巢狀的四段動畫(左移 15、右移 30、左移 15、回到中心),並以迴圈重複數次,就能得到類似左右搖晃的效果。把 shock() 綁到登入失敗的時機觸發,即可為表單加上生動的錯誤提示。