fadeIn() 是 fadeOut() 的逆向操作,它針對 display:none 的元素,讓透明度從 0 遞增至 1 並顯示出來。常用於模態視窗、提示訊息、圖片載入完成後的呈現。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn(); // 預設 400ms
$("#div2").fadeIn("slow"); // 600ms
$("#div3").fadeIn(3000); // 3000ms
});
});
</script>
</head>
<body>
<p>Demonstrate fadeIn() with different parameters.</p>
<button>Click to fade in boxes</button>
<br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>
</html>
注意三個 div 的 style 裡都有 display:none——這是 fadeIn() 生效的前提。若元素本來可見,呼叫 fadeIn 不會有任何變化。
兩者都會把元素顯示出來,但 show() 是瞬間的,fadeIn() 有透明度過渡。此外 show() 會把 display 還原成「該元素在樣式表中最終計算出的值」,而 fadeIn 動畫結束後也會恢復成合適的 display 型別,因此對 inline 元素也能正確處理。
$("#gallery img").each(function(){
var img = new Image();
img.onload = function(){
$(this).hide().attr("src", img.src).fadeIn(400);
};
img.src = $(this).data("src");
});
$(".item").each(function(i){
$(this).hide().delay(i * 120).fadeIn(400);
});
這會讓列表項目依序錯開浮現,是很常見的入場效果。
.stop(true, true) 清空佇列,否則會看到元素反覆閃爍。把 fadeIn/fadeOut 搭配 delay 與 stop,幾乎所有「出現—停留—消失」的提示型互動都能乾淨地完成。