.fadeOut() 通過 漸變 opacity 至 0 並最終設置 display: none,實現元素「淡出消失」效果。屬於 jQuery 核心淡入淡出動畫族(配合 .fadeIn()、.fadeToggle()、.fadeTo())。
.fadeOut([duration] [, easing] [, complete])
// duration: 'fast'(200) | 'slow'(600) | 毫秒數 | 預設 400
// easing: 'swing' (默認) | 'linear' | 自定義 easing 函數
// complete: 動畫結束回調 function() {}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>fadeOut 速度對比</title>
<style>
.box { width: 80px; height: 80px; margin: 10px; float: left; }
#div1 { background: #e74c3c; } /* 紅 - 默認速度 */
#div2 { background: #f39c12; } /* 橙 - slow */
#div3 { background: #3498db; } /* 藍 - 3000ms */
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p>點擊按鈕觀察三種速度淡出效果</p>
<button id="btn-fade">同時淡出三個色塊</button>
<br><br>
<div id="div1" class="box"></div>
<div id="div2" class="box"></div>
<div id="div3" class="box"></div>
<script>
$('#btn-fade').click(function() {
$('#div1').fadeOut(); // 默認 400ms
$('#div2').fadeOut('slow'); // 600ms
$('#div3').fadeOut(3000); // 3000ms (3秒)
});
</script>
</body>
</html>
$('#modal').fadeOut(300, function() {
$(this).remove(); // 從 DOM 移除
enablePageScroll(); // 恢復頁面滾動
});
async function hideAndNotify($el) {
await $el.fadeOut(400).promise();
showToast('已關閉');
}
// 用戶快速點擊關閉,避免動畫排隊
$('#closeBtn').click(function() {
$('#panel').stop(true, true).fadeOut(200);
});
// fadeOut 會最終 display:none,若需保留佔位:
$('#element').animate({ opacity: 0 }, 400); // 不改變 display
// 或 CSS: .fade-out { opacity: 0; transition: opacity .4s; pointer-events: none; }
| 維度 | jQuery fadeOut | CSS opacity + transition |
|---|---|---|
| 性能 | JS 主線程逐幀計算,可能掉幀 | GPU 加速,極度流暢 |
| display:none 處理 | 自動處理 | 需手動監聽 transitionend 設置 |
| 動態速度/條件 | 極易實現 | 需操作 style/類名,稍繁瑣 |
| 舊瀏覽器兼容 | 完美(IE6+) | IE9+ 需前綴,IE8- 不支持 |
| 推薦場景 | 複雜邏輯、舊專案、需精確回調控制 | 現代項目、簡單淡入淡出、追求 60fps |
/* CSS */
.fade-enter { opacity: 0; transition: opacity 0.3s ease; }
.fade-leave { opacity: 1; transition: opacity 0.3s ease; }
.fade-leave-active { opacity: 0; pointer-events: none; }
/* JS 只需切換類名 */
function fadeOut($el) {
$el.addClass('fade-leave').removeClass('fade-enter');
// 可選:監聽 transitionend 後 $el.hide()
}
display:none 元素 .fadeOut() 直接返回,需先 .show() 或 .css('display','block')。display:none 導致文檔流重排,周圍元素跳動。解決:容器預留高度、或用 visibility:hidden 替代。pointer-events: none 或動畫前 .css('pointer-events','none')。.fadeOut() 同一元素會排隊。用 .stop(true) 清空隊列。setTimeout(() => $toast.fadeOut(300), 3000)。.fadeOut(),回調中 .remove()。onload 後 $placeholder.fadeOut()。$error.fadeOut(2000)。.fadeOut() 是 jQuery 中實現淡出最語義化的方法,自動處理 display:none 收尾。現代開發中,簡單淡入淡出優先 CSS Transition(性能、流暢度優勢);複雜序列控制、條件邏輯、舊環境兼容 時,.fadeOut() 依然是高效可靠的選擇。掌握其隊列、停止、Promise 化、與 CSS 協作模式,是前端動畫工程化必備技能。