DIV CSS 佈局教程網

jQuery fadeOut():用不同參數控制元素淡出速度
編輯:JavaScript綜合知識     

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);
  • duration:毫秒數字,或 slow(600)/normal(400)/fast(200)。
  • easing:可選,預設 swing;linear 則是等速衰減。
  • callback:動畫結束後執行的函式,此時元素已經真正不可見。

fadeOut() 與 hide() 的差別

兩者最終都會讓元素變成 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 設定,在此情形下直接跳過動畫。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved