想讓兩張圖片柔和地互相切換,其實不需要動畫函式庫。jQuery 內建的 fadeOut 與 fadeIn 就夠了,關鍵是把它們綁在正確的事件上,並處理好動畫的銜接。
結構上只有一個容器包著一張圖:
<div id="kitten">
<img src="/images/kitten.jpg" alt="Kitten" />
</div>
接著用 hover 一次掛上移入與移出兩個處理器:
$("#kitten").hover(function () {
$(this).find("img").fadeOut();
}, function () {
$(this).find("img").fadeIn();
});
滑鼠移進容器時圖片淡出、移開時淡回。若把 fadeOut 的完成回呼裡換成另一張圖的 src,就變成真正的「換圖」:
$("#kitten").hover(function () {
var $img = $(this).find("img");
$img.stop(true, true).fadeOut(300, function () {
$(this).attr("src", "/images/kitten-alt.jpg").fadeIn(300);
});
}, function () {
$(this).find("img").stop(true, true).fadeIn(300);
});
jQuery 的動畫是佇列式的。使用者快速反覆移入移出時,動畫會一條條排隊等著播放,畫面就會出現「跑一半又倒回去」的怪現象。stop(true, true) 的兩個參數分別代表「清空後續佇列」與「立刻跳到目前動畫的終點」,加上它之後互動就會乾淨俐落。
上面的做法有個空檔:淡出結束後才開始淡入,中間會露出背景。若要兩張圖真正重疊交叉,讓它們同時存在於 DOM 中,用絕對定位疊起來再交叉控制透明度:
<div id="kitten">
<img class="front" src="/images/kitten.jpg" alt="Kitten" />
<img class="back" src="/images/kitten-alt.jpg" alt="Kitten alt" />
</div>
#kitten { position: relative; }
#kitten img { position: absolute; top: 0; left: 0; }
#kitten .back { display: none; }
$("#kitten").hover(function () {
$(this).find(".front").stop(true, true).fadeOut(400);
$(this).find(".back").stop(true, true).fadeIn(400);
}, function () {
$(this).find(".front").stop(true, true).fadeIn(400);
$(this).find(".back").stop(true, true).fadeOut(400);
});
兩張圖各跑一條動畫,透明度此消彼長,視覺上就完全沒有斷層。記得幫容器設好固定高度,否則圖片改成絕對定位後容器會塌掉。