jQuery 提供多種動畫方法,讓開發者能快速為頁面加入動態效果。常見方法包含 show()、hide()、fadeIn()、fadeOut()、slideUp()、slideDown() 與 animate()。
$('h1').show();
$('h1').hide();
hide() 等同於將元素的 display 設為 none。show() 則會恢復顯示。
$('div.old').fadeIn(300);
$('div.old').fadeOut(300, function () {
$(this).remove();
});
fadeOut() 完成後,可以在回呼函式中執行後續操作,例如移除元素。
animate() 可以用來建立自訂動畫:
$('div.funtimes').animate({
left: '+=50',
opacity: 0.25
}, 300, function () {
console.log('done!');
});
若需要停止動畫,可使用 stop();若要延遲執行,可使用 delay():
$('h1').show(300).delay(1000).hide(300);
$('#id').stop().animate({ left: '400px' }, 3000);
jQuery 動畫適合快速建立互動效果,但在複雜專案中,也可考慮 CSS transition 或 Web Animations API。