JavaScript插件

Bootstrap自带了13个jQuery插件,这些插件为Bootstrap中的组件赋予了“生命”。

引入单个插件还是一次性引入所有插件

每个插件都可以单独的引入到页面中(注意插件间的依赖关系),或者一次性引入。bootstrap.jsbootstrap.min.js 文件都将所有插件包含在一个文件中了(前者是未压缩版,后者是压缩版)。

Data 属性

你可以仅仅通过data属性API就能使用所有Bootstrap中的插件,而且不用写一行JavaScript代码。这是Bootstrap中的一等API,并且是你的首选方式。

特殊情况是,在某些情况下可能需要特意禁用这种默认动作。因此,我们特地提供了禁用data属性API的方式,通过解除绑定在body上的被命名为`'data-api'`的事件即可实现。如下所示:

$('body').off('.data-api')

还可以解除特定插件的事件绑定,只要将插件名和data-api链接在一起作为参数使用。如下所示:

$('body').off('.alert.data-api')

编程API

我们同时为所有Bootstrap插件提供了JavaScript API。所有公开的API都可以单独或链式调用,均返回其所操作的集合(和jQuery的API一致)。

$(".btn.danger").button("toggle").addClass("fat")

所有方法均可接受一个可选的参数对象、一个对此方法有特定意义的字符串或者什么也不传(即用默认参数初始化此插件):

$("#myModal").modal()                       // initialized with defaults
$("#myModal").modal({ keyboard: false })   // initialized with no keyboard
$("#myModal").modal('show')                // initializes and invokes show immediately

每个插件都通过`Constructor` 属性暴露了其原始的构造函数:$.fn.popover.Constructor。如果你想获得某个特定插件的实例,可以直接从页面元素中获取:$('[rel=popover]').data('popover').

No Conflict

有时你需要在使用Bootstrap插件时同时使用其它UI框架。在这种情况下,随时都会导致命名空间冲突。如果这种情况发生了,你可以通过调用插件的 .noConflict 函数恢复其原始值。

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

事件

Bootstrap对多数插件的独有行为提供了自定义事件。 一般而言,这些事件都是以(英语)动词的原型和过去分词形式来表示的 - 动词原形形式的(例如: show) 在事件执行之前触发;过去分词形式的(例如:shown) 在动作执行完毕后触发。

所有动词原形形式的事件都提供了preventDefault函数。这能在动作执行之前使其停止。

$('#myModal').on('show', function (e) {
    if (!data) return e.preventDefault() // stops modal from being shown
})

关于过渡效果

对于简单的过度效果,只要在引入其它JS文件时一同引入bootstrap-transition.js文件即可。如果你引入的是编译(或压缩)之后的bootstrap.js文件,就不再需要引入此文件了,因为bootstrap.js文件已经包含了此插件。

使用案例

过渡效果插件的使用案例:

  • 具有幻灯片或淡入效果的对话框
  • 具有淡出效果的标签页
  • 具有淡出效果的警告框
  • 具有幻灯片效果的轮播板

案例

模态对话框是一类简洁、灵活的的弹框,他们具有精简的功能和友好的默认行为。

静态案例

带有标题、正文、页脚按钮的对话框。

<div class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3>对话框标题</h3>
  </div>
  <div class="modal-body">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <a href="#" class="btn">关闭</a>
    <a href="#" class="btn btn-primary">Save changes</a>
  </div>
</div>

动态演示

点击下面的按钮会通过javascript触发一个模态对话框。对话框从页面顶端滑下的同时逐渐呈现。

<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">查看演示案例</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>

调用方式

通过data属性

无需编写JavaScript代码即可生成一个对话框。在一个主控元素,例如按钮,上设置data-toggle="modal",然后再设置data-target="#foo"href="#foo" 用以指向某个将要被启动的对话框。

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

通过JavaScript

仅用一行JavaScript代码即可启动id为myModal的对话框:

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

选项

上面的选项都可以通过data属性或JavaScript代码传递给组件。对于data属性,将选项名称附着于data-字符串之后,就像data-backdrop=""一样。

名称 类型 默认值 描述
backdrop boolean true Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn't close the modal on click.
keyboard boolean true Closes the modal when escape key is pressed
show boolean true Shows the modal when initialized.
remote path false

If a remote url is provided, content will be loaded via jQuery's load method and injected into the .modal-body. If you're using the data api, you may alternatively use the href tag to specify the remote source. An example of this is shown below:

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

方法

.modal(options)

让你指定的内容变成一个模态对话框。接受一个可选的参数object.

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

.modal('toggle')

手动打开或隐藏一个模态对话框。

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

.modal('show')

手动打开一个模态对话框。

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

.modal('hide')

手动隐藏一个模态对话框。

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

事件

Bootstrap中的模态对话框对外暴露了一些事件允许你监听。

事件 描述
show This event fires immediately when the show instance method is called.
shown This event is fired when the modal has been made visible to the user (will wait for css transitions to complete).
hide This event is fired immediately when the hide instance method has been called.
hidden This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).
$('#myModal').on('hidden', function () {
  // do something…
})

用在导航条上

ScrollSpy插件根据滚动的位置自动更新导航条中相应的导航项。拖动下面区域的滚动条,使其低于导航条的位置,注意观察active类的变化。下拉菜单中的子项也会跟着变为高亮状态。

@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.


调用方式

通过data属性

只需将data-spy="scroll"添加到被监听的页面元素上(大部分情况是添加到body上),然后将data-target=".navbar"添加到导航部分,仅此而已,顶部导航条就拥有了监听滚动的功能。你可能希望将滚动监听应用到.nav组件上。

<body data-spy="scroll" data-target=".navbar">...</body>

通过JavaScript

通过JavaScript启动滚动监听:

$('#navbar').scrollspy()
注意! 必须为导航条中的链接指定相应的目标id。例如,<a href="#home">home</a>必须和dom中类似<div id="home"></div>的页面元素相呼应。

方法

.scrollspy('refresh')

当滚动监听所作用的DOM有增删页面元素的操作时,需要调用下面的refresh方法:

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

选项

所有参数都可以通过data属性或JavaScript传递。对于data属性,将参数名附着到data-后面,就像data-offset=""一样。

名称 类型 默认值 描述
offset number 10 Pixels to offset from top when calculating position of scroll.

事件

Event Description
activate This event fires whenever a new item becomes activated by the scrollspy.

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.

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.


调用方式

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

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

You can activate individual tabs in several ways:

$('#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.

<ul class="nav nav-tabs">
  <li><a href="#home" data-toggle="tab">首页</a></li>
  <li><a href="#profile" data-toggle="tab">Profile</a></li>
  <li><a href="#messages" data-toggle="tab">Messages</a></li>
  <li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>

方法

$().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.

<ul class="nav nav-tabs" id="myTab">
  <li class="active"><a href="#home">首页</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home">...</div>
  <div class="tab-pane" id="profile">...</div>
  <div class="tab-pane" id="messages">...</div>
  <div class="tab-pane" id="settings">...</div>
</div>

<script>
  $(function () {
    $('#myTab a:last').tab('show');
  })
</script>

事件

Event Description
show This event fires on tab show, but before the new tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.
shown 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.
$('a[data-toggle="tab"]').on('shown', function (e) {
  e.target // activated tab
  e.relatedTarget // previous tab
})

案例

本插件受到Jason Frame开发的jQuery.tipsy插件的启发。Tooltips做了很多改进,例如不需要依赖图片,而是改用CSS3实现动画效果,用data属性存储标题信息。

由于性能的原因,For performance reasons, the tooltip and popover data-apis are opt in, meaning you must initialize them yourself.

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.

Four directions

Tooltips in input groups

When using tooltips and popovers with the Bootstrap input groups, you'll have to set the container (documented below) option to avoid unwanted side effects.


调用方式

通过JavaScript触发工具提示:

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

选项

可以通过data属性或JavaScript传递参数。对于data属性,将参数名附着到data-后面即可,例如, data-animation=""

名称 类型 默认值 描述
animation boolean true apply a css fade transition to the tooltip
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
selector string false If a selector is provided, tooltip objects will be delegated to the specified targets.
title string | function '' default title value if `title` tag isn't present
trigger string 'hover focus' how tooltip is triggered - click | hover | focus | manual. Note you case pass trigger mutliple, space seperated, trigger types.
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 }

container string | false false

Appends the tooltip to a specific element container: 'body'

注意! 可以针对单个工具提示指定单独的data属性。

标记

<a href="#" data-toggle="tooltip" title="first tooltip">hover over me</a>

方法

$().tooltip(options)

对一组页面元素绑定一个工具提示处理器。

.tooltip('show')

弹出某个页面元素的工具提示。

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

.tooltip('hide')

隐藏某个页面元素的工具提示。

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

.tooltip('toggle')

打开或隐藏某个页面元素的工具提示。

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

.tooltip('destroy')

隐藏并销毁某个页面元素的工具提示。

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

案例

下面

对任意页面元素添加一个覆盖层展示额外信息,就行iPad中的类似功能。将鼠标悬停在下面的按钮上即可触发一个弹出提示。必须先引入 工具提示 插件

静态弹出提示

有4个可选参数:top、right、bottom和left 对其方式。

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.

No markup shown as popovers are generated from JavaScript and content within a data attribute.

Live demo

Four directions


调用方式

通过JavaScript启用弹出提示:

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

选项

可以通过data属性或JavaScript传递参数。对于data属性,将参数名附着到data-之后,例如data-animation=""

名称 类型 默认值 描述
animation boolean true apply a css fade transition to the tooltip
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
selector string false if a selector is provided, tooltip objects will be delegated to the specified targets
trigger string 'click' how popover is triggered - click | hover | focus | manual
title string | function '' default title value if `title` attribute isn't present
content string | function '' default content value if `data-content` attribute isn't present
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 }

container string | false false

Appends the popover to a specific element container: 'body'

Heads up! Options for individual popovers can alternatively be specified through the use of data attributes.

标记

For performance reasons, the Tooltip and Popover data-apis are opt in. If you would like to use them just specify a selector option.

方法

$().popover(options)

对一组页面元素初始化弹出提示。

.popover('show')

打开某个页面元素的弹出提示。

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

.popover('hide')

隐藏某个页面元素的弹出提示。

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

.popover('toggle')

打开或隐藏某个页面元素的弹出提示。

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

.popover('destroy')

隐藏并销毁某个页面元素的弹出提示。

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

警告框案例

利用此插件对所有警告消息添加取消功能。

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.

Take this action Or do this


调用方式

通过JavaScript为某个警告框添加取消功能:

$(".alert").alert()

标记

仅需将data-dismiss="alert"添加到关闭按钮即可自动赋予某个警告框关闭的功能。

<a class="close" data-dismiss="alert" href="#">&times;</a>

方法

$().alert()

赋予所有警告框以关闭功能。如果你希望警告框在关闭时带有动画效果,请确保.fade.in类已经应用到这些警告框上了。

.alert('close')

关闭某个警告框。

$(".alert").alert('close')

事件

Bootstrap中的警告框对外暴露了一些事件允许你监听。

Event Description
close This event fires immediately when the close instance method is called.
closed This event is fired when the alert has been closed (will wait for css transitions to complete).
$('#my-alert').bind('closed', function () {
  // do something…
})

使用案例

按钮可以实现很多功能。为工具条(toolbar)之类的组件赋予控制按钮的状态或者创建一组按钮的功能。

Stateful

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

<button type="button" class="btn btn-primary" data-loading-text="Loading...">Loading state</button>

Single toggle

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

<button type="button" class="btn btn-primary" data-toggle="button">Single Toggle</button>

Checkbox

Add data-toggle="buttons-checkbox" for checkbox style toggling on btn-group.

<div class="btn-group" data-toggle="buttons-checkbox">
  <button type="button" class="btn btn-primary">Left</button>
  <button type="button" class="btn btn-primary">Middle</button>
  <button type="button" class="btn btn-primary">Right</button>
</div>

Radio

Add data-toggle="buttons-radio" for radio style toggling on btn-group.

<div class="btn-group" data-toggle="buttons-radio">
  <button type="button" class="btn btn-primary">Left</button>
  <button type="button" class="btn btn-primary">Middle</button>
  <button type="button" class="btn btn-primary">Right</button>
</div>

调用方式

Enable buttons via JavaScript:

$('.nav-tabs').button()

Markup

Data attributes are integral to the button plugin. Check out the example code below for the various markup types.

选项

方法

$().button('toggle')

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

Heads up! You can enable auto toggling of a button by using the data-toggle attribute.
<button type="button" class="btn" data-toggle="button" >…</button>

$().button('loading')

Sets button state to loading - disables button and swaps text to loading text. Loading text should be defined on the button element using the data attribute data-loading-text.

<button type="button" class="btn" data-loading-text="loading stuff..." >...</button>
Heads up! Firefox persists the disabled state across page loads. A workaround for this is to use autocomplete="off".

$().button('reset')

Resets button state - swaps text to original text.

$().button(string)

Resets button state - swaps text to any data defined text state.

<button type="button" class="btn" data-complete-text="finished!" >...</button>
<script>
  $('.btn').button('complete')
</script>

About