fadeOut() 藉由逐步降低 opacity 並最終設為 display:none,做出元素「淡出消失」的效果。它接受速度參數,讓你能為不同元素設定不同的消失節奏。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeOut(); // 預設 400ms
$("#div2").fadeOut("slow"); // 600ms
$("#div3").fadeOut(3000); // 3000ms
});
});
</script>
</head>
<body>
<p>Demonstrate fadeOut() with different parameters.</p>
<button>Click to fade out boxes</button>
<br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>
</html>
$("#el").fadeOut(duration, easing, callback);
兩者最終都會讓元素變成 display:none,差別只在過程:hide() 是瞬間消失(除非帶入參數變成高度收合動畫),fadeOut() 則有透明度遞減的過場。視覺上淡出通常比直接消失柔和,適合提示訊息、通知列這類元素。
function showToast(msg){
var $t = $('<div class="toast"></div>').text(msg).appendTo("body");
$t.fadeIn(200).delay(2000).fadeOut(400, function(){
$(this).remove();
});
}
這裡用 .text() 而非 .html() 寫入訊息,避免使用者提供的內容造成 XSS。
動畫佇列:連續觸發會排隊,加上 .stop(true, true) 可避免延遲播放。
fadeOut 後元素仍佔記憶體:它只是隱藏,元素還在 DOM 裡。若確定不再需要,在 callback 中 remove() 才是真正釋放。
可訪問性:頻繁閃動的淡入淡出對部分使用者會造成不適,可尊重系統的 prefers-reduced-motion 設定,在此情形下直接跳過動畫。