JavaScript 插件

概覽

單個仍是所有引入

JavaScript 插件能夠單個引入(使用 Bootstrap 提供的單個 *.js 文件),或者一次性所有引入(使用 bootstrap.js 或壓縮版的 bootstrap.min.js)。javascript

建議使用壓縮版的 JavaScript 文件

bootstrap.js 和 bootstrap.min.js 都包含了全部插件,你在使用時,只需選擇一個引入頁面就能夠了。css

組件的 data 屬性

不要在同一個元素上同時使用多個插件的 data 屬性。例如,button 組件不能同時支持工具提示和控制模態框。若是須要的話,能夠在其外面包裹一個額外的元素。html

插件之間的依賴關係

某些插件和 CSS 組件依賴於其它插件。若是你是單個引入每一個插件的,請確保在文檔中檢查插件之間的依賴關係。注意,全部插件都依賴 jQuery (也就是說,jQuery必須在全部插件以前引入頁面)。 bower.json 文件中列出了 Bootstrap 所支持的 jQuery 版本。java

data 屬性

你能夠僅僅經過 data 屬性 API 就能使用全部的 Bootstrap 插件,無需寫一行 JavaScript 代碼。這是 Bootstrap 中的一等 API,也應該是你的首選方式。node

話又說回來,在某些狀況下可能須要將此功能關閉。所以,咱們還提供了關閉 data 屬性 API 的方法,即解除以 data-api 爲命名空間並綁定在文檔上的事件。就像下面這樣:react

Copy
$(document).off('.data-api') 

另外,若是是針對某個特定的插件,只需在 data-api 前面添加那個插件的名稱做爲命名空間,以下:jquery

Copy
$(document).off('.alert.data-api') 

編程方式的 API

咱們爲全部 Bootstrap 插件提供了純 JavaScript 方式的 API。全部公開的 API 都是支持單獨或鏈式調用方式,而且返回其所操做的元素集合(注:和jQuery的調用形式一致)。git

Copy
$('.btn.danger').button('toggle').addClass('fat') 

全部方法均可以接受一個可選的 option 對象做爲參數,或者一個表明特定方法的字符串,或者什麼也不提供(在這種狀況下,插件將會以默認值初始化):github

Copy
$('#myModal').modal() // 以默認值初始化 $('#myModal').modal({ keyboard: false }) // initialized with no keyboard $('#myModal').modal('show') // 初始化後當即調用 show 方法 

每一個插件還經過 Constructor 屬性暴露了其原始的構造函數:$.fn.popover.Constructor。若是你想獲取某個插件的實例,能夠直接經過頁面元素獲取:$('[rel="popover"]').data('popover')編程

默認設置

每一個插件均可以經過修改其自身的 Constructor.DEFAULTS 對象從而改變插件的默認設置:

 

Copy
$.fn.modal.Constructor.DEFAULTS.keyboard = false // 將模態框插件的 `keyboard` 默認選參數置爲 false 

避免命名空間衝突

某些時候可能須要將 Bootstrap 插件與其餘 UI 框架共同使用。在這種狀況下,命名空間衝突隨時可能發生。若是不幸發生了這種狀況,你能夠經過調用插件的 .noConflict 方法恢復其原始值。

Copy
var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value $.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality 

事件

Bootstrap 爲大部分插件所具備的動做提供了自定義事件。通常來講,這些事件都有不定式和過去式兩種動詞的命名形式,例如,不定式形式的動詞(例如 show)表示其在事件開始時被觸發;而過去式動詞(例如 shown )表示在動做執行完畢以後被觸發。

從 3.0.0 版本開始,全部 Bootstrap 事件的名稱都採用命名空間方式。

全部以不定式形式的動詞命名的事件都提供了 preventDefault 功能。這就賦予你在動做開始執行前將其中止的能力。

Copy
$('#myModal').on('show.bs.modal', function (e) { if (!data) return e.preventDefault() // 阻止模態框的展現 }) 

未對禁用 JavaScript 的瀏覽器提供補救措施

Bootstrap 插件未對禁用 JavaScript 的瀏覽器提供補救措施。若是你對這種狀況下的用戶體驗很關心的話,請添加<noscript> 標籤向你的用戶進行解釋(並告訴他們如何啓用 JavaScript),或者按照你本身的方式提供補救措施。

第三方工具庫

Bootstrap 官方不提供對第三方 JavaScript 工具庫的支持,例如 Prototype 或 jQuery UI。除了 .noConflict 和爲事件名稱添加命名空間,還可能會有兼容性方面的問題,這就須要你本身來處理了。

過渡效果 transition.js

關於過渡效果

對於簡單的過渡效果,只需將 transition.js 和其它 JS 文件一塊兒引入便可。若是你使用的是編譯(或壓縮)版的bootstrap.js 文件,就無需再單獨將其引入了。

包含的內容

Transition.js 是針對 transitionEnd 事件的一個基本輔助工具,也是對 CSS 過渡效果的模擬。它被其它插件用來檢測當前瀏覽器對是否支持 CSS 的過渡效果。

模態框 modal.js

模態框通過了優化,更加靈活,以彈出對話框的形式出現,具備最小和最實用的功能集。

不支持模態框重疊

千萬不要在一個模態框上重疊另外一個模態框。要想同時支持多個模態框,須要本身寫額外的代碼來實現。

模態框的 HTML 代碼放置的位置

務必將模態框的 HTML 代碼放在文檔的最高層級內(也就是說,儘可能做爲 body 標籤的直接子元素),以免其餘組件影響模態框的展示和/或功能。

對於移動設備的附加說明

這裏提供了在移動設備上使用模態框有一些附加說明。請參考瀏覽器支持章節。

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals.

實例

靜態實例

如下模態框包含了模態框的頭、體和一組放置於底部的按鈕。

Copy
<div class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <p>One fine body&hellip;</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> 

動態實例

點擊下面的按鈕便可經過 JavaScript 啓動一個模態框。此模態框將從上到下、逐漸浮現到頁面前。

Copy
<!-- Button trigger modal --> <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> 

加強模態框的可訪問性

務必爲 .modal 添加 role="dialog" 屬性,aria-labelledby="myModalLabel" 屬性用於只想模態框的標題欄,aria-hidden="true" 用於通知輔助性工具略過模態框的 DOM元素。

另外,你還應該經過 aria-describedby 屬性爲模態框 .modal 添加描述性信息。

嵌入 YouTube 視頻(天朝無用)

在模態框中嵌入 YouTube 視頻須要增長一些額外的 JavaScript 代碼,用於自動中止重放等功能,這些代碼並無在 Bootstrap 中提供。請參考這份發佈在 Stack Overflow 上的文章

可選尺寸

模態框提供了兩個可選尺寸,經過爲 .modal-dialog 增長一個樣式調整類實現。

 
Copy
<!-- Large modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large modal</button> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ... </div> </div> </div> <!-- Small modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal</button> <div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> ... </div> </div> </div> 

禁止動畫效果

若是你不須要模態框彈出時的動畫效果(淡入淡出效果),刪掉 .fade 類便可。

Copy
<div class="modal" tabindex="-1" role="dialog" aria-labelledby="" aria-hidden="true"> ... </div> 

用法

經過 data 屬性或 JavaScript 調用模態框插件,能夠根據須要動態展現隱藏的內容。模態框彈出時還會爲 <body> 元素添加 .modal-open 類,從而覆蓋頁面默認的滾動行爲,而且還會自動生成一個 .modal-backdrop 元素用於提供一個可點擊的區域,點擊此區域就便可關閉模態框。

經過 data 屬性

不需寫 JavaScript 代碼也可激活模態框。經過在一個起控制器做用的元素(例如:按鈕)上添加 data-toggle="modal"屬性,或者 data-target="#foo" 屬性,再或者 href="#foo" 屬性,用於指向被控制的模態框。

Copy
<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button> 

經過 JavaScript 調用

只需一行 JavaScript 代碼,便可經過元素的 id myModal 調用模態框:

Copy
$('#myModal').modal(options) 

參數

能夠將選項經過 data 屬性或 JavaScript 代碼傳遞。對於 data 屬性,須要將參數名稱放到 data- 以後,例如 data-backdrop=""

名稱 類型 默認值 描述
backdrop boolean 或 字符串'static' true Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn't close the modal on click.
keyboard boolean true 鍵盤上的 esc 鍵被按下時關閉模態框。
show boolean true 模態框初始化以後就當即顯示出來。
remote path false

This option is deprecated since v3.2.1 and will be removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

若是提供的是 URL,將利用 jQuery 的 load 方法今後 URL 地址加載要展現的內容(只加載一次)並插入 .modal-content 內。若是使用的是 data 屬性 API,還能夠利用 href 屬性指定內容來源地址。下面是一個實例:

Copy
<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a> 

方法

.modal(options)

將頁面中的某塊內容做爲模態框激活。接受可選參數 object

Copy
$('#myModal').modal({ keyboard: false }) 

.modal('toggle')

手動打開或關閉模態框。在模態框顯示或隱藏以前返回到主調函數中(也就是,在觸發 shown.bs.modal 或hidden.bs.modal 事件以前)。

Copy
$('#myModal').modal('toggle') 

.modal('show')

手動打開模態框。在模態框顯示以前返回到主調函數中 (也就是,在觸發 shown.bs.modal 事件以前)。

Copy
$('#myModal').modal('show') 

.modal('hide')

手動隱藏模態框。在模態框隱藏以前返回到主調函數中 (也就是,在觸發 hidden.bs.modal 事件以前)。

Copy
$('#myModal').modal('hide') 

事件

Bootstrap 的模態框類提供了一些事件用於監聽並執行你本身的代碼。

事件類型 描述
show.bs.modal show 方法調用以後當即觸發該事件。若是是經過點擊某個做爲觸發器的元素,則此元素能夠經過事件的relatedTarget 屬性進行訪問。
shown.bs.modal 此事件在模態框已經顯示出來(而且同時在 CSS 過渡效果完成)以後被觸發。若是是經過點擊某個做爲觸發器的元素,則此元素能夠經過事件的 relatedTarget 屬性進行訪問。
hide.bs.modal hide 方法調用以後當即觸發該事件。
hidden.bs.modal 此事件在模態框被隱藏(而且同時在 CSS 過渡效果完成)以後被觸發。
loaded.bs.modal 遠端的數據源加載完數據以後觸發該事件。
Copy
$('#myModal').on('hidden.bs.modal', function (e) { // do something... }) 

Dropdowns dropdown.js

Add dropdown menus to nearly anything with this simple plugin, including the navbar, tabs, and pills.

Within a navbar

Within pills

Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the .openclass on the parent list item.

On mobile devices, opening a dropdown adds a .dropdown-backdrop as a tap area for closing dropdown menus when tapping outside the menu, a requirement for proper iOS support. This means that switching from an open dropdown menu to a different dropdown menu requires an extra tap on mobile.

Note: The data-toggle="dropdown" attribute is relied on for closing dropdown menus at an application level, so it's a good idea to always use it.

Via data attributes

Add data-toggle="dropdown" to a link or button to toggle a dropdown.

Copy
<div class="dropdown"> <button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown trigger <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> ... </ul> </div> 

To keep URLs intact with link buttons, use the data-target attribute instead of href="#".

Copy
<div class="dropdown"> <a id="dLabel" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown trigger <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> ... </ul> </div> 

Via JavaScript

Call the dropdowns via JavaScript:

Copy
$('.dropdown-toggle').dropdown() 

data-toggle="dropdown" still required

Regardless of whether you call your dropdown via JavaScript or instead use the data-api, data-toggle="dropdown"is always required to be present on the dropdown's trigger element.

Options

None

Methods

$().dropdown('toggle')

Toggles the dropdown menu of a given navbar or tabbed navigation.

Events

All dropdown events are fired at the .dropdown-menu's parent element.

Event Type Description
show.bs.dropdown This event fires immediately when the show instance method is called. The toggling anchor element is available as the relatedTarget property of the event.
shown.bs.dropdown This event is fired when the dropdown has been made visible to the user (will wait for CSS transitions, to complete). The toggling anchor element is available as the relatedTarget property of the event.
hide.bs.dropdown This event is fired immediately when the hide instance method has been called. The toggling anchor element is available as the relatedTarget property of the event.
hidden.bs.dropdown This event is fired when the dropdown has finished being hidden from the user (will wait for CSS transitions, to complete). The toggling anchor element is available as the relatedTarget property of the event.
Copy
$('#myDropdown').on('show.bs.dropdown', function () { // do something… }) 

ScrollSpy scrollspy.js

Example in navbar

The ScrollSpy plugin is for automatically updating nav targets based on scroll position. Scroll the area below the navbar and watch the active class change. The dropdown sub items will be highlighted as well.

@fat

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

@mdo

Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.

one

Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.

two

In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.

three

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.

Usage

Requires Bootstrap nav

Scrollspy currently requires the use of a Bootstrap nav component for proper highlighting of active links.

Requires relative positioning

No matter the implementation method, scrollspy requires the use of position: relative; on the element you're spying on. In most cases this is the <body>.

Via data attributes

To easily add scrollspy behavior to your topbar navigation, add data-spy="scroll" to the element you want to spy on (most typically this would be the <body>). Then add the data-target attribute with the ID or class of the parent element of any Bootstrap .nav component.

Copy
body { position: relative; } 
Copy
<body data-spy="scroll" data-target=".navbar-example"> ... <div class="navbar-example"> <ul class="nav nav-tabs" role="tablist"> ... </ul> </div> ... </body> 

Via JavaScript

After adding position: relative; in your CSS, call the scrollspy via JavaScript:

Copy
$('body').scrollspy({ target: '.navbar-example' }) 

Resolvable ID targets required

Navbar links must have resolvable id targets. For example, a <a href="#home">home</a> must correspond to something in the DOM like <div id="home"></div>.

Non-:visible target elements ignored

Target elements that are not :visible according to jQuery will be ignored and their corresponding nav items will never be highlighted.

Methods

.scrollspy('refresh')

When using scrollspy in conjunction with adding or removing of elements from the DOM, you'll need to call the refresh method like so:

Copy
$('[data-spy="scroll"]').each(function () { var $spy = $(this).scrollspy('refresh') }) 

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as indata-offset="".

Name type default description
offset number 10 Pixels to offset from top when calculating position of scroll.

Events

Event Type Description
activate.bs.scrollspy This event fires whenever a new item becomes activated by the scrollspy.
Copy
$('#myScrollspy').on('activate.bs.scrollspy', function () { // do something… }) 

Togglable tabs tab.js

Example tabs

Add quick, dynamic tab functionality to transition through panes of local content, even via dropdown menus.

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

Extends tabbed navigation

This plugin extends the tabbed navigation component to add tabbable areas.

Usage

Enable tabbable tabs via JavaScript (each tab needs to be activated individually):

Copy
$('#myTab a').click(function (e) { e.preventDefault() $(this).tab('show') }) 

You can activate individual tabs in several ways:

Copy
$('#myTab a[href="#profile"]').tab('show') // Select tab by name $('#myTab a:first').tab('show') // Select first tab $('#myTab a:last').tab('show') // Select last tab $('#myTab li:eq(2) a').tab('show') // Select third tab (0-indexed) 

Markup

You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element. Adding the nav and nav-tabs classes to the tab ul will apply the Bootstrap tab styling, while adding the nav and nav-pills classes will apply pill styling.

Copy
<!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="tab">Home</a></li> <li role="presentation"><a href="#profile" role="tab" data-toggle="tab">Profile</a></li> <li role="presentation"><a href="#messages" role="tab" data-toggle="tab">Messages</a></li> <li role="presentation"><a href="#settings" role="tab" data-toggle="tab">Settings</a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home">...</div> <div role="tabpanel" class="tab-pane" id="profile">...</div> <div role="tabpanel" class="tab-pane" id="messages">...</div> <div role="tabpanel" class="tab-pane" id="settings">...</div> </div> 

Fade effect

To make tabs fade in, add .fade to each .tab-pane. The first tab pane must also have .in to properly fade in initial content.

Copy
<div class="tab-content"> <div role="tabpanel" class="tab-pane fade in active" id="home">...</div> <div role="tabpanel" class="tab-pane fade" id="profile">...</div> <div role="tabpanel" class="tab-pane fade" id="messages">...</div> <div role="tabpanel" class="tab-pane fade" id="settings">...</div> </div> 

Methods

$().tab

Activates a tab element and content container. Tab should have either a data-target or an href targeting a container node in the DOM.

Copy
<ul class="nav nav-tabs" role="tablist" id="myTab"> <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="tab">Home</a></li> <li role="presentation"><a href="#profile" role="tab" data-toggle="tab">Profile</a></li> <li role="presentation"><a href="#messages" role="tab" data-toggle="tab">Messages</a></li> <li role="presentation"><a href="#settings" role="tab" data-toggle="tab">Settings</a></li> </ul> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home">...</div> <div role="tabpanel" class="tab-pane" id="profile">...</div> <div role="tabpanel" class="tab-pane" id="messages">...</div> <div role="tabpanel" class="tab-pane" id="settings">...</div> </div> <script> $(function () { $('#myTab a:last').tab('show') }) </script> 

Events

When showing a new tab, the events fire in the following order:

  1. hide.bs.tab (on the current active tab)
  2. show.bs.tab (on the to-be-shown tab)
  3. hidden.bs.tab (on the previous active tab, the same one as for the hide.bs.tab event)
  4. shown.bs.tab (on the newly-active just-shown tab, the same one as for the show.bs.tab event)

If no tab was already active, then the hide.bs.tab and hidden.bs.tab events will not be fired.

Event Type Description
show.bs.tab This event fires on tab show, but before the new tab has been shown. Use event.target andevent.relatedTarget to target the active tab and the previous active tab (if available) respectively.
shown.bs.tab This event fires on tab show after a tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.
hide.bs.tab This event fires when a new tab is to be shown (and thus the previous active tab is to be hidden). Useevent.target and event.relatedTarget to target the current active tab and the new soon-to-be-active tab, respectively.
hidden.bs.tab This event fires after a new tab is shown (and thus the previous active tab is hidden). Use event.targetand event.relatedTarget to target the previous active tab and the new active tab, respectively.
Copy
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { e.target // newly activated tab e.relatedTarget // previous active tab }) 

Tooltips tooltip.js

Inspired by the excellent jQuery.tipsy plugin written by Jason Frame; Tooltips are an updated version, which don't rely on images, use CSS3 for animations, and data-attributes for local title storage.

Tooltips with zero-length titles are never displayed.

Examples

Hover over the links below to see tooltips:

Tight pants next level keffiyeh you probably haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel have a terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A really ironic artisan whatever keytar, scenester farm-to-table banksy Austin twitter handle freegan cred raw denim single-origin coffee viral.

Static tooltip

Four options are available: top, right, bottom, and left aligned.

 
Tooltip on the left
 
 
Tooltip on the top
 
 
Tooltip on the bottom
 
 
Tooltip on the right

Four directions

     
Copy
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left">Tooltip on left</button> <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Tooltip on top</button> <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom">Tooltip on bottom</button> <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right">Tooltip on right</button> 

Opt-in functionality

For performance reasons, the Tooltip and Popover data-apis are opt-in, meaning you must initialize them yourself.

Tooltips in button groups and input groups require special setting

When using tooltips on elements within a .btn-group or an .input-group, you'll have to specify the optioncontainer: 'body' (documented below) to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the tooltip is triggered).

Don't try to show tooltips on hidden elements

Invoking $(...).tooltip('show') when the target element is display: none; will cause the tooltip to be incorrectly positioned.

Tooltips on disabled elements require wrapper elements

To add a tooltip to a disabled or .disabled element, put the element inside of a <div> and apply the tooltip to that <div> instead.

Usage

The tooltip plugin generates content and markup on demand, and by default places tooltips after their trigger element.

Trigger the tooltip via JavaScript:

Copy
$('#example').tooltip(options) 

Markup

The required markup for a tooltip is only a data attribute and title on the HTML element you wish to have a tooltip. The generated markup of a tooltip is rather simple, though it does require a position (by default, set to top by the plugin).

Multiple-line links

Sometimes you want to add a tooltip to a hyperlink that wraps multiple lines. The default behavior of the tooltip plugin is to center it horizontally and vertically. Add white-space: nowrap; to your anchors to avoid this.

Copy
<!-- HTML to write --> <a href="#" data-toggle="tooltip" title="Some tooltip text!">Hover over me</a> <!-- Generated markup by the plugin --> <div class="tooltip top" role="tooltip"> <div class="tooltip-arrow"></div> <div class="tooltip-inner"> Some tooltip text! </div> </div> 

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as indata-animation="".

Name Type Default Description
animation boolean true Apply a CSS fade transition to the tooltip
container string | false false

Appends the tooltip to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the tooltip in the flow of the document near the triggering element - which will prevent the tooltip from floating away from the triggering element during a window resize.

delay number | object 0

Delay showing and hiding the tooltip (ms) - does not apply to manual trigger type

If a number is supplied, delay is applied to both hide/show

Object structure is: delay: { "show": 500, "hide": 100 }

html boolean false Insert HTML into the tooltip. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
placement string | function 'top'

How to position the tooltip - top | bottom | left | right | auto.
When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right.

When a function is used to determine the placement, it is called with the tooltip DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the tooltip instance.

selector string false If a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added. See this and an informative example.
template string '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'

Base HTML to use when creating the tooltip.

The tooltip's title will be injected into the .tooltip-inner.

.tooltip-arrow will become the tooltip's arrow.

The outermost wrapper element should have the .tooltip class.

title string | function ''

Default title value if title attribute isn't present.

If a function is given, it will be called with its this reference set to the element that the tooltip is attached to.

trigger string 'hover focus' How tooltip is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space.
viewport string | object { selector: 'body', padding: 0 }

Keeps the tooltip within the bounds of this element. Example: viewport: '#viewport' or { "selector": "#viewport", "padding": 0 }

Data attributes for individual tooltips

Options for individual tooltips can alternatively be specified through the use of data attributes, as explained above.

Methods

$().tooltip(options)

Attaches a tooltip handler to an element collection.

.tooltip('show')

Reveals an element's tooltip. Tooltips with zero-length titles are never displayed.

Copy
$('#element').tooltip('show') 

.tooltip('hide')

Hides an element's tooltip.

Copy
$('#element').tooltip('hide') 

.tooltip('toggle')

Toggles an element's tooltip.

Copy
$('#element').tooltip('toggle') 

.tooltip('destroy')

Hides and destroys an element's tooltip.

Copy
$('#element').tooltip('destroy') 

Events

Event Type Description
show.bs.tooltip This event fires immediately when the show instance method is called.
shown.bs.tooltip This event is fired when the tooltip has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.tooltip This event is fired immediately when the hide instance method has been called.
hidden.bs.tooltip This event is fired when the tooltip has finished being hidden from the user (will wait for CSS transitions to complete).
Copy
$('#myTooltip').on('hidden.bs.tooltip', function () { // do something… }) 

Popovers popover.js

Examples

Add small overlays of content, like those on the iPad, to any element for housing secondary information.

Popovers whose both title and content are zero-length are never displayed.

Plugin dependency

Popovers require the tooltip plugin to be included in your version of Bootstrap.

Opt-in functionality

For performance reasons, the Tooltip and Popover data-apis are opt-in, meaning you must initialize them yourself.

Popovers in button groups and input groups require special setting

When using popovers on elements within a .btn-group or an .input-group, you'll have to specify the optioncontainer: 'body' (documented below) to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the popover is triggered).

Don't try to show popovers on hidden elements

Invoking $(...).popover('show') when the target element is display: none; will cause the popover to be incorrectly positioned.

Popovers on disabled elements require wrapper elements

To add a popover to a disabled or .disabled element, put the element inside of a <div> and apply the popover to that <div> instead.

Multiple-line links

Sometimes you want to add a popover to a hyperlink that wraps multiple lines. The default behavior of the popover plugin is to center it horizontally and vertically. Add white-space: nowrap; to your anchors to avoid this.

Static popover

Four options are available: top, right, bottom, and left aligned.

 

Popover top

Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.

 

Popover right

Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.

 

Popover bottom

Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.

 

Popover left

Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.

 

Live demo

Copy
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button> 

Four directions

     
Copy
<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."> Popover on left </button> <button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."> Popover on top </button> <button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="bottom" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."> Popover on bottom </button> <button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="right" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."> Popover on right </button> 

Dismiss on next click

Use the focus trigger to dismiss popovers on the next click that the user makes.

Specific markup required for dismiss-on-next-click

For proper cross-browser and cross-platform behavior, you must use the <a> tag, not the <button> tag, and you also must include a tabindex attribute.

Copy
<a href="#" tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="Dismissible popover" data-content="And here's some amazing content. It's very engaging. Right?">Dismissible popover</a> 

Usage

Enable popovers via JavaScript:

Copy
$('#example').popover(options) 

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as indata-animation="".

Name Type Default Description
animation boolean true Apply a CSS fade transition to the popover
container string | false false

Appends the popover to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the popover in the flow of the document near the triggering element - which will prevent the popover from floating away from the triggering element during a window resize.

content string | function ''

Default content value if data-content attribute isn't present.

If a function is given, it will be called with its this reference set to the element that the popover is attached to.

delay number | object 0

Delay showing and hiding the popover (ms) - does not apply to manual trigger type

If a number is supplied, delay is applied to both hide/show

Object structure is: delay: { "show": 500, "hide": 100 }

html boolean false Insert HTML into the popover. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
placement string | function 'right'

How to position the popover - top | bottom | left | right | auto.
When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the popover will display to the left when possible, otherwise it will display right.

When a function is used to determine the placement, it is called with the popover DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the popover instance.

selector string false If a selector is provided, popover objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have popovers added. See this and an informative example.
template string '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'

Base HTML to use when creating the popover.

The popover's title will be injected into the .popover-title.

The popover's content will be injected into the .popover-content.

.arrow will become the popover's arrow.

The outermost wrapper element should have the .popover class.

title string | function ''

Default title value if title attribute isn't present.

If a function is given, it will be called with its this reference set to the element that the popover is attached to.

trigger string 'click' How popover is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space.
viewport string | object { selector: 'body', padding: 0 }

Keeps the popover within the bounds of this element. Example: viewport: '#viewport' or { "selector": "#viewport", "padding": 0 }

Data attributes for individual popovers

Options for individual popovers can alternatively be specified through the use of data attributes, as explained above.

Methods

$().popover(options)

Initializes popovers for an element collection.

.popover('show')

Reveals an element's popover. Popovers whose both title and content are zero-length are never displayed.

Copy
$('#element').popover('show') 

.popover('hide')

Hides an element's popover.

Copy
$('#element').popover('hide') 

.popover('toggle')

Toggles an element's popover.

Copy
$('#element').popover('toggle') 

.popover('destroy')

Hides and destroys an element's popover.

Copy
$('#element').popover('destroy') 

Events

Event Type Description
show.bs.popover This event fires immediately when the show instance method is called.
shown.bs.popover This event is fired when the popover has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.popover This event is fired immediately when the hide instance method has been called.
hidden.bs.popover This event is fired when the popover has finished being hidden from the user (will wait for CSS transitions to complete).
Copy
$('#myPopover').on('hidden.bs.popover', function () { // do something… }) 

警告框 alert.js

警告框實例

Add dismiss functionality to all alert messages with this plugin.

When using a .close button, it must be the first child of the .alert-dismissible and no text content may come before it in the markup.

Holy guacamole! Best check yo self, you're not looking too good.

Oh snap! You got an error!

Change this and that and try again. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum.

 

用法

Just add data-dismiss="alert" to your close button to automatically give an alert close functionality. Closing an alert removes it from the DOM.

Copy
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> 
Copy
<button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> 

To have your alerts use animation when closing, make sure they have the .fade and .in classes already applied to them.

Methods

$().alert()

Makes an alert listen for click events on descendant elements which have the data-dismiss="alert" attribute. (Not necessary when using the data-api's auto-initialization.)

$().alert('close')

Closes an alert by removing it from the DOM. If the .fade and .in classes are present on the element, the alert will fade out before it is removed.

Events

Bootstrap's alert plugin exposes a few events for hooking into alert functionality.

Event Type Description
close.bs.alert This event fires immediately when the close instance method is called.
closed.bs.alert This event is fired when the alert has been closed (will wait for CSS transitions to complete).
Copy
$('#myAlert').on('closed.bs.alert', function () { // do something… }) 

Buttons button.js

Do more with buttons. Control button states or create groups of buttons for more components like toolbars.

Cross-browser compatibility

Firefox persists form control states (disabledness and checkedness) across page loads. A workaround for this is to use autocomplete="off". See Mozilla bug #654072.

Stateful

Add data-loading-text="Loading..." to use a loading state on a button.

Use whichever state you like!

For the sake of this demonstration, we are using data-loading-text and $().button('loading'), but that's not the only state you can use. See more on this below in the $().button(string) documentation.

Copy
<button type="button" id="myButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off"> Loading state </button> <script> $('#myButton').on('click', function () { var $btn = $(this).button('loading') // business logic... $btn.button('reset') }) </script> 

Single toggle

Add data-toggle="button" to activate toggling on a single button.

Copy
<button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Single toggle </button> 

Pre-toggled buttons need .active and aria-pressed="true"

For pre-toggled buttons, you must add the .active class and the aria-pressed="true" attribute to the buttonyourself.

Checkbox / Radio

Add data-toggle="buttons" to a .btn-group containing checkbox or radio inputs to enable toggling in their respective styles.

Preselected options need .active

For preselected options, you must add the .active class to the input's label yourself.

Visual checked state only updated on click

If the checked state of a checkbox button is updated without firing a click event on the button (e.g. via <input type="reset"> or via setting the checked property of the input), you will need to toggle the .active class on the input's label yourself.

Copy
<div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked) </label> <label class="btn btn-primary"> <input type="checkbox" autocomplete="off"> Checkbox 2 </label> <label class="btn btn-primary"> <input type="checkbox" autocomplete="off"> Checkbox 3 </label> </div> 
Copy
<div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected) </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2 </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3 </label> </div> 

Methods

$().button('toggle')

Toggles push state. Gives the button the appearance that it has been activated.

$().button('reset')

Resets button state - swaps text to original text.

$().button(string)

Swaps text to any data defined text state.

Copy
<button type="button" id="myStateButton" data-complete-text="finished!" class="btn btn-primary" autocomplete="off"> ... </button> <script> $('#myStateButton').on('click', function () { $(this).button('complete') // button text will be "finished!" }) </script> 

Collapse collapse.js

About

Get base styles and flexible support for collapsible components like accordions and navigation.

Plugin dependency

Collapse requires the transitions plugin to be included in your version of Bootstrap.

Example accordion

Using the collapse plugin, we built a simple accordion by extending the panel component.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
Copy
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingTwo"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Collapsible Group Item #2 </a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingThree"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Collapsible Group Item #3 </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree"> <div class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> </div> 

It's also possible to swap out .panel-bodys with .list-groups.

You can also use the plugin without the accordion markup. Make a button toggle the expanding and collapsing of another element.

Copy
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#demo" aria-expanded="true" aria-controls="demo"> simple collapsible </button> <div id="demo" class="collapse in">...</div> 

Make expand/collapse controls accessible

Be sure to add aria-expanded to the control element. This attribute explicitly defines the current state of the collapsible element to screen readers and similar assistive technologies. If the collapsible element is closed by default, it should have a value of aria-expanded="false". If you've set the collapsible element to be open by default using the in class, set aria-expanded="true" on the control instead. The plugin will automatically toggle this attribute based on whether or not the collapsible element has been opened or closed.

Additionally, if your control element is targetting a single collapsible element – i.e. the data-target attribute is pointing to an id selector – you may add an additional aria-controls attribute to the control element, containing the id of the collapsible element. Modern screen readers and similar assistive technologies make use of this attribute to provide users with additional shortcuts to navigate directly to the collapsible element itself.

Usage

The collapse plugin utilizes a few classes to handle the heavy lifting:

  • .collapse hides the content
  • .collapse.in shows the content
  • .collapsing is added when the transition starts, and removed when it finishes

These classes can be found in component-animations.less.

Via data attributes

Just add data-toggle="collapse" and a data-target to the element to automatically assign control of a collapsible element. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapseto the collapsible element. If you'd like it to default open, add the additional class in.

To add accordion-like group management to a collapsible control, add the data attribute data-parent="#selector". Refer to the demo to see this in action.

Via JavaScript

Enable manually with:

Copy
$('.collapse').collapse() 

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as indata-parent="".

Name type default description
parent selector false If a selector is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior - this is dependent on the panel class)
toggle boolean true Toggles the collapsible element on invocation

Methods

.collapse(options)

Activates your content as a collapsible element. Accepts an optional options object.

Copy
$('#myCollapsible').collapse({ toggle: false }) 

.collapse('toggle')

Toggles a collapsible element to shown or hidden.

.collapse('show')

Shows a collapsible element.

.collapse('hide')

Hides a collapsible element.

Events

Bootstrap's collapse class exposes a few events for hooking into collapse functionality.

Event Type Description
show.bs.collapse This event fires immediately when the show instance method is called.
shown.bs.collapse This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.collapse This event is fired immediately when the hide method has been called.
hidden.bs.collapse This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).
Copy
$('#myCollapsible').on('hidden.bs.collapse', function () { // do something… }) 

Carousel carousel.js

A slideshow component for cycling through elemnts, like a carousel. Nested carousels are not supported.

Copy
<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"> <div class="item active"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> <div class="item"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> ... </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></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"></span> <span class="sr-only">Next</span> </a> </div> 

Optional captions

Add captions to your slides easily with the .carousel-caption element within any .item. Place just about any optional HTML within there and it will be automatically aligned and formatted.

Copy
<div class="item"> <img src="..." alt="..."> <div class="carousel-caption"> <h3>...</h3> <p>...</p> </div> </div> 

Accessibility issue

The carousel component is generally not compliant with accessibility standards. If you need to be compliant, please consider other options for presenting your content.

Multiple carousels

Carousels require the use of an id on the outermost container (the .carousel) for carousel controls to function properly. When adding multiple carousels, or when changing a carousel's id, be sure to update the relevant controls.

Via data attributes

Use data attributes to easily control the position of the carousel. data-slide accepts the keywords prev or next, which alters the slide position relative to its current position. Alternatively, use data-slide-to to pass a raw slide index to the carousel data-slide-to="2", which shifts the slide position to a particular index beginning with 0.

The data-ride="carousel" attribute is used to mark a carousel as animating starting at page load. It cannot be used in combination with (redundant and unnecessary) explicit JavaScript initialization of the same carousel.

Via JavaScript

Call carousel manually with:

Copy
$('.carousel').carousel() 

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as indata-interval="".

Name type default description
interval number 5000 The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.
pause string "hover" Pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.
wrap boolean true Whether the carousel should cycle continuously or have hard stops.
keyboard boolean true Whether the carousel should react to keyboard events.

Methods

.carousel(options)

Initializes the carousel with an optional options object and starts cycling through items.

Copy
$('.carousel').carousel({ interval: 2000 }) 

.carousel('cycle')

Cycles through the carousel items from left to right.

.carousel('pause')

Stops the carousel from cycling through items.

.carousel(number)

Cycles the carousel to a particular frame (0 based, similar to an array).

.carousel('prev')

Cycles to the previous item.

.carousel('next')

Cycles to the next item.

Events

Bootstrap's carousel class exposes two events for hooking into carousel functionality.

Both events have the following additional properties:

  • direction: The direction in which the carousel is sliding (either "left" or "right").
  • relatedTarget: The DOM element that is being slid into place as the active item.
Event Type Description
slide.bs.carousel This event fires immediately when the slide instance method is invoked.
slid.bs.carousel This event is fired when the carousel has completed its slide transition.
Copy
$('#myCarousel').on('slide.bs.carousel', function () { // do something… }) 

Affix affix.js

Example

The subnavigation on the right is a live demo of the affix plugin.


Usage

Use the affix plugin via data attributes or manually with your own JavaScript. In both situations, you must provide CSS for the positioning and width of your affixed content.

Positioning via CSS

The affix plugin toggles between three classes, each representing a particular state: .affix.affix-top, and .affix-bottom. You must provide the styles for these classes yourself (independent of this plugin) to handle the actual positions.

Here's how the affix plugin works:

  1. To start, the plugin adds .affix-top to indicate the element is in its top-most position. At this point no CSS positioning is required.
  2. Scrolling past the element you want affixed should trigger the actual affixing. This is where .affix replaces .affix-top and sets position: fixed; (provided by Bootstrap's CSS).
  3. If a bottom offset is defined, scrolling past it should replace .affix with .affix-bottom. Since offsets are optional, setting one requires you to set the appropriate CSS. In this case, add position: absolute; when necessary. The plugin uses the data attribute or JavaScript option to determine where to position the element from there.

Follow the above steps to set your CSS for either of the usage options below.

Via data attributes

To easily add affix behavior to any element, just add data-spy="affix" to the element you want to spy on. Use offsets to define when to toggle the pinning of an element.

Copy
<div data-spy="affix" data-offset-top="60" data-offset-bottom="200"> ... </div> 

Via JavaScript

Call the affix plugin via JavaScript:

Copy
$('#myAffix').affix({ offset: { top: 100, bottom: function () { return (this.bottom = $('.footer').outerHeight(true)) } } }) 

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as indata-offset-top="200".

Name type default description
offset number | function | object 10 Pixels to offset from screen when calculating position of scroll. If a single number is provided, the offset will be applied in both top and bottom directions. To provide a unique, bottom and top offset just provide an object offset: { top: 10 } or offset: { top: 10, bottom: 5 }. Use a function when you need to dynamically calculate an offset.
target selector | node | jQuery element thewindowobject Specifies the target element of the affix.

Events

Bootstrap's affix plugin exposes a few events for hooking into affix functionality.

Event Type Description
affix.bs.affix This event fires immediately before the element has been affixed.
affixed.bs.affix This event is fired after the element has been affixed.
affix-top.bs.affix This event fires immediately before the element has been affixed-top.
affixed-top.bs.affix This event is fired after the element has been affixed-top.
affix-bottom.bs.affix This event fires immediately before the element has been affixed-bottom.
affixed-bottom.bs.affix This event is fired after the element has been affixed-bottom.
相關文章
相關標籤/搜索