一般的焦點圖輪播,切換動畫從頭到尾都是同一種節奏,看久了會有點單調。本文的做法是搭配 jquery.easing 外掛,在每次動畫結束時隨機挑一個新的緩動函數作為下一次的切換效果,讓每一輪都有不同的手感。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="https://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
<script src="js/slides.min.jquery.js"></script>
<script>
$(function(){
// 收集 easing 外掛提供的所有緩動函數名稱
var easings = [];
var row = 0;
for(var x in jQuery.easing){
if (x != 'linear' && x != 'swing') {
easings[row++] = x;
}
}
$('#slides').slides({
preload: true,
preloadImage: 'img/loading.gif',
play: 5000,
pause: 2500,
slideEasing: "swing",
slideSpeed : 2000,
hoverPause: true,
animationComplete: function(current) {
// 動畫結束後隨機換一個緩動函數
var index = Math.floor(Math.random() * easings.length);
jQuery.easing.def = easings[index];
}
});
});
</script>
<div id="container">
<div id="example">
<img src="img/new-ribbon.png" width="112" height="112" alt="New Ribbon" id="ribbon">
<div id="slides">
<div class="slides_container">
<a href="#" title="Slide 1" target="_blank">
<img src="img/slide-1.jpg" width="570" height="270" alt="Slide 1">
</a>
<a href="#" title="Slide 2" target="_blank">
<img src="img/slide-2.jpg" width="570" height="270" alt="Slide 2">
</a>
<!-- 其餘圖片依此類推 -->
</div>
<a href="#" class="prev"><img src="img/arrow-prev.png" width="24" height="43" alt="Arrow Prev"></a>
<a href="#" class="next"><img src="img/arrow-next.png" width="24" height="43" alt="Arrow Next"></a>
</div>
<img src="img/example-frame.png" width="739" height="341" alt="Example Frame" id="frame">
</div>
</div>
整個技巧只靠兩個環節。
第一,把 easing 外掛的函數全部枚舉出來。jquery.easing 是一個以函數名稱為 key 的物件,用 for...in 就能把所有名稱收集成陣列。這裡刻意排除 linear 與 swing——linear 是等速、沒有加減速感,swing 則是 jQuery 的預設值,留著它們會讓隨機結果出現「看起來沒變」的情況。
第二,在 animationComplete 回呼裡改寫 jQuery.easing.def。def 是 jQuery 動畫使用的預設緩動函數,slides 外掛內部若未明確指定 easing,就會讀這個值。因此每當一次切換結束,我們就抽一個新名字寫進去,下一輪自然就換了手感。
參數部分也值得留意:play 是自動播放間隔、pause 是切換後的停頓、slideSpeed 控制動畫時長、hoverPause 讓滑鼠移入時暫停。把 slideSpeed 設大一點(例如 2000 毫秒)才能明顯感受到不同 easing 的差異——太快的動畫會讓 easeInBack 與 easeOutBounce 看起來差不多。
若想避免連續兩次抽到同一個效果,可以在抽完後把該名稱從陣列中移除,抽完一整輪再重新填回。另外,easing 1.3 已相當老舊,新專案建議改用 jQuery Easing 的後繼版本或直接搭配 CSS transition 的 cubic-bezier 來達到類似效果。