很多時候,若你的專案只需要一個輕量級的輪播、不需要太多功能,同時又採用 Bootstrap(最受歡迎的開源前端框架之一),那麼不妨參考 Bootstrap 官方元件,再搭配 CSS3 動畫讓效果更出色。
為了讓動畫效果更精彩,我使用了 Dan Eden 所寫的知名開源 CSS3 動畫庫 animate.css。它讓我能專注於手邊的任務,而不必費心撰寫 CSS3 動畫程式碼。
使用 Animate.css 只需兩個步驟:
在 HTML 文件中引入 animate.min.css;接著在要套用動畫的元素上加入 animated 與 yourchosenanimation 兩個類別,並以 Animate.css 網站上的動畫類名取代 yourchosenanimation。
Bootstrap 輪播元件主要有三個部分:

想深入了解 Bootstrap 輪播元件,可參考 Syed Fazle Rahman 撰寫的《用 Bootstrap3 建立 JS 輪播效果》。為了簡化示範,這裡先不加圖片,把焦點放在輪播框架與動畫上。
你需要專案中引用:jQuery、Bootstrap 的 CSS 與 JavaScript、Animate.css,以及一份自訂樣式表與 JS 檔。為加快開發,可直接從 Bootstrap 官網引用模板與必要檔案。以下是輪播程式碼:
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"> </li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <!-- First slide --> <div class="item active"> <div class="carousel-caption"> <h3 data-animation="animated bounceInLeft"> This is the caption for slide 1 </h3> <h3 data-animation="animated bounceInRight"> This is the caption for slide 1 </h3> <button class="btn btn-primary btn-lg" data-animation="animated zoomInUp">Button</button> </div> </div><!-- /.item --> <!-- Second slide --> <div class="item"> <div class="carousel-caption"> <h3 class="icon-container" data-animation="animated bounceInDown"> <span class="glyphicon glyphicon-heart"></span> </h3> <h3 data-animation="animated bounceInUp"> This is the caption for slide 2 </h3> <button class="btn btn-primary btn-lg" data-animation="animated zoomInRight">Button</button> </div> </div><!-- /.item --> <!-- Third slide --> <div class="item"> <div class="carousel-caption"> <h3 class="icon-container" data-animation="animated zoomInLeft"> <span class="glyphicon glyphicon-glass"></span> </h3> <h3 data-animation="animated flipInX"> This is the caption for slide 3 </h3> <button class="btn btn-primary btn-lg" data-animation="animated lightSpeedIn">Button</button> </div> </div><!-- /.item --> </div><!-- /.carousel-inner --> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div><!-- /.carousel -->
若以上程式碼無誤,在瀏覽器打開就會看到一個可運行的輪播,且尚未寫入任何 JavaScript。若不加入圖片,只需在 CSS 中為 .carousel .item 加上 min-height 防止輪播塌陷即可。
接著在輪播標題內的元素上加上 data-animation 屬性,並以動畫類名作為它的值;想體驗其他動畫,只需替換 data-animation 的值即可。由於我們打算用 JavaScript 控制輪播,因此可移除 data-ride="carousel" 屬性。
接著依自己的喜好為標題添加樣式。更具體地說,我們透過 animation-delay 控制每個動畫的起始時間(為簡化示範,省略瀏覽器前綴):
.carousel-caption h3:first-child { animation-delay: 1s; } .carousel-caption h3:nth-child(2) { animation-delay: 2s; } .carousel-caption button { animation-delay: 3s; }
如此可確保元素動畫有序開始,你也可以自行調整,例如讓前兩個標題同時出現、再顯示按鈕。
先初始化輪播:
var $myCarousel = $('#carousel-example-generic'); // Initialize carousel $myCarousel.carousel();
為了讓第一張幻燈片的標題在頁面載入後就有動畫,而後續幻燈片在切換進入時也有動畫,我們的程式碼需要在 slide.bs.carousel 事件上執行,也就是頁面載入一次、事件觸發一次。由於我們遵循不重複的原則,會把程式碼封裝在函式中並在適當時機呼叫。
function doAnimations(elems) { var animEndEv = 'webkitAnimationEnd animationend'; elems.each(function () { var $this = $(this), $animationType = $this.data('animation'); // Add animate.css classes to // the elements to be animated // Remove animate.css classes // once the animation event has ended $this.addClass($animationType).one(animEndEv, function () { $this.removeClass($animationType); }); }); } // Select the elements to be animated // in the first slide on page load var $firstAnimatingElems = $myCarousel.find('.item:first') .find('[data-animation ^= "animated"]'); // Apply the animation using our function doAnimations($firstAnimatingElems); // Pause the carousel $myCarousel.carousel('pause'); // Attach our doAnimations() function to the // carousel's slide.bs.carousel event $myCarousel.on('slide.bs.carousel', function (e) { // Select the elements to be animated inside the active slide var $animatingElems = $(e.relatedTarget) .find("[data-animation ^= 'animated']"); doAnimations($animatingElems); });
以下逐一說明這段程式碼。
1、doAnimations() 函式
它首先快取包含 animationend 事件名稱的字串。這個事件告訴我們動畫何時結束,因為每次動畫結束後我們都要移除 animate.css 類別;若不移除,標題就只會在第一次顯示該幻燈片時才有動畫。
var animEndEv = 'webkitAnimationEnd animationend';
接著函式遍歷每個要套用動畫的元素,取得 data-animation 屬性值(即要加入的 animate.css 類別):
elems.each(function () { var $this = $(this), $animationType = $this.data('animation'); // etc... });
最後,doAnimations() 為每個元素動態加上 animate.css 類別,並附加一個事件監聽,在動畫結束後移除該類別,確保下一次輪播回到當前區域時仍能重新播放動畫。
$this.addClass($animationType).one(animEndEv, function () { $this.removeClass($animationType); });
2、第一個標題的動畫
當頁面載入時,我們為第一張幻燈片中要動畫的內容套用動畫:
var $firstAnimatingElems = $myCarousel.find('.item:first') .find("[data-animation ^= 'animated']"); doAnimations($firstAnimatingElems);
這裡先找到第一張幻燈片,取出要動畫的標題元素,再將 $firstAnimatingElems 作為參數傳給 doAnimations() 執行。
3、輪播的停止功能
第一張幻燈片的動畫執行完畢後,我們停止輪播:
$myCarousel.carousel('pause');
這是 Bootstrap 輪播元件防止不停旋轉的特性,因為不斷旋轉可能讓訪客生厭。此時可透過 interval 選項控制間隔,確保動畫播完前不會直接跳到下一張:
$myCarousel.carousel({ interval: 4000 });
4、輪播幻燈片標題的動畫
為每張幻燈片的標題套用動畫,需要以下步驟。首先在 slide.bs.carousel 上加上事件監聽器,當幻燈片方法被呼叫時該事件會立即觸發:
$myCarousel.on('slide.bs.carousel', function (e) { // do stuff... });
接著選取當前幻燈片並找出要動畫的元素,這裡用事件的 relatedTarget 屬性來定位:
var $animatingElems = $(e.relatedTarget).find("[data-animation ^= 'animated']");
最後呼叫 doAnimations(),把 $animatingElems 作為參數傳入:
doAnimations($animatingElems);
本文展示了如何運用幾行 jQuery 與 animate.css 庫,為基本的 Bootstrap 輪播元件加上動畫效果。當然,其他類似的 CSS 庫或 CSS3 動畫也能達到相同目的,希望本文能帶給大家更多啟發,打開學習思路。
若想深入學習,也可參考 Bootstrap 學習教程與 Bootstrap 實戰教程等專題。