DIV CSS 佈局教程網

用 Bootstrap 打造圖片輪播:完整實例與參數說明
編輯:關於JavaScript     

先看一下成品長什麼樣,如果效果符合你的需求,再往下看實作細節。

一、結構說明

Bootstrap 的輪播元件由三個部分組成:指示器(carousel-indicators,也就是底部的小圓點)、輪播內容(carousel-inner 內的每個 item)、以及左右切換控制鈕(carousel-control)。三者都要透過 data-target 指向同一個 id,才算綁在同一組輪播上。

二、完整程式碼

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>圖片輪播_01</title> <link href="../bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet"> <script src="../js/jquery-2.1.4.min.js"></script> <script src="../bootstrap-3.3.5-dist/js/bootstrap.min.js"></script> </head> <body> <!-- interval 為每張停留毫秒數;此元件亦支援鍵盤左右方向鍵切換 --> <div class="container"> <div style="width:960px;height:400px;margin:auto;"> <div id="carousel-example-generic" class="carousel slide"> <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> <li data-target="#carousel-example-generic" data-slide-to="3"></li> </ol> <div class="carousel-inner"> <div class="item active"> <img src="../img/圖片輪播/pic01.jpg" /> </div> <div class="item"> <img src="../img/圖片輪播/pic02.jpg" /> <!-- 圖片上的說明文字 --> <div class="carousel-caption"> <h3>聯想校園大使</h3></div> </div> <div class="item"> <img src="../img/圖片輪播/pic03.jpg" /> </div> <div class="item"> <img src="../img/圖片輪播/pic04.jpg" /> </div> </div> <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> </div> </div> <!-- 用 JavaScript 設定輪播間隔,相對於靜態設定更能確保自動播放啟動 --> <script> $(".carousel").carousel({ interval: 4000 }) </script> </body> </html>

三、幾個容易出錯的地方

第一張必須帶 active。無論是 .carousel-inner 下的第一個 .item,還是指示器中的第一個 <li>,都要加上 active,否則頁面載入時會是一片空白。

演算法式的 class 差一個字就失效。carousel slide 少了 slide 就沒有滑動動畫,會變成硬切換。

高度要自己決定。Bootstrap 不會替你撐開容器,圖片尺寸不一樣時畫面會跳動,實務上建議先固定容器寬高,再讓圖片 width:100% 填滿。

jQuery 別忘了載入。輪播屬於 JS 外掛,缺少 jQuery 會直接失效,而且順序必須在 bootstrap.min.js 之前。

以上就是以 Bootstrap 實作圖片輪播的完整示範。若想進一步自訂,可以改用 carousel('pause') 讓滑鼠移入時暫停,或搭配 slid.bs.carousel 事件做額外處理。

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