Bootstrap中的JavaScript

原文地址 http://caibaojian.com/bootstrap/javascript.html

Bootstrap中的JavaScript

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

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

Data 属性

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

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

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

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

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

编程API

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

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

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

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

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

No Conflict

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

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

事件

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

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

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

过渡效果 bootstrap-transition.js

关于过渡效果

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

使用案例

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

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

模态对话框 bootstrap-modal.js

案例

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

静态案例

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

对话框标题

One fine body…

  1. class="modal hide fade">
  2. class="modal-header">
  3. 对话框标题

  4. class="modal-body">
  5. One fine body…

  6. class="modal-footer">
  7. href="#" class="btn">关闭
  8. href="#" class="btn btn-primary">Save changes

动态演示

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

  1. href="#myModal" role="button" class="btn" data-toggle="modal">查看演示案例
  2.  
  3. id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  4. class="modal-header">
  5. id="myModalLabel">Modal header

  6. class="modal-body">
  7. One fine body…

  8. class="modal-footer">

调用方式

通过data属性

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

通过JavaScript

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

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

  1. data-toggle="modal" href="remote.html" data-target="#modal">click me

方法

.modal(options)

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

  1. $('#myModal').modal({
  2. keyboard: false
  3. })
.modal('toggle')

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

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

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

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

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

  1. $('#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).
  1. $('#myModal').on('hidden', function () {
  2. // do something…
  3. })

下拉菜单 bootstrap-dropdown.js

案例

通过此插件可以将下拉菜单加入到任何其他组件中,包括导航条、标签页。

导航条中的下拉菜单

标签页中的下拉菜单。


调用方式

通过data属性

在链接或按钮上添加data-toggle="dropdown"即可切换下拉菜单。

  1. class="dropdown">
  2. class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger
    • class="dropdown-menu" role="menu" aria-labelledby="dLabel">
    • ...

为了保证URL符合规范,请使用data-target属性来代替href="#"

  1. class="dropdown">
  2. class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#"href="/page.html">
  3. Dropdown
  4. class="caret">
    • class="dropdown-menu" role="menu" aria-labelledby="dLabel">
    • ...

通过JavaScript

通过JavaScript调用下拉菜单:

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

选项

方法

$().dropdown('toggle')

通过编程式api对某个特定的导航条或标签页导航切换下拉菜单。

滚动监听 bootstrap-scrollspy.js

用在导航条上

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组件上。

  1. data-spy="scroll" data-target=".navbar">...

通过JavaScript

通过JavaScript启动滚动监听:

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

方法

.scrollspy('refresh')

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

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

选项

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

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

事件

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

Togglable tabs bootstrap-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.


调用方式

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

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

You can activate individual tabs in several ways:

  1. $('#myTab a[href="#profile"]').tab('show'); // Select tab by name
  2. $('#myTab a:first').tab('show'); // Select first tab
  3. $('#myTab a:last').tab('show'); // Select last tab
  4. $('#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.

  1. href="#profile" data-toggle="tab">Profile
  2. href="#messages" data-toggle="tab">Messages
  3. href="#settings" data-toggle="tab">Settings

方法

$().tab

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

  1. href="#profile">Profile
  2. href="#messages">Messages
  3. href="#settings">Settings
  4.  
  5. class="tab-content">
  6. class="tab-pane active" id="home">...
  7. class="tab-pane" id="profile">...
  8. class="tab-pane" id="messages">...
  9. class="tab-pane" id="settings">...
  10.  
  11. $(function () {
  12. $('#myTab a:last').tab('show');
  13. })

事件

EventDescription
show This event fires on tab show, but before the new tab has been shown. Use event.targetand 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.
  1. $('a[data-toggle="tab"]').on('shown', function (e) {
  2. e.target // activated tab
  3. e.relatedTarget // previous tab
  4. })

工具提示 bootstrap-tooltip.js

案例

本插件受到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 handlefreegan 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触发工具提示:

  1. $('#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属性。

标记

  1. href="#" data-toggle="tooltip" title="first tooltip">hover over me

方法

$().tooltip(options)

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

.tooltip('show')

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

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

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

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

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

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

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

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

弹出提示 bootstrap-popover.js

案例

下面

对任意页面元素添加一个覆盖层展示额外信息,就行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启用弹出提示:

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

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

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

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

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

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

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

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

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

警告消息 bootstrap-alert.js

警告框案例

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

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为某个警告框添加取消功能:

  1. $(".alert").alert()

标记

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

  1. class="close" data-dismiss="alert" href="#">×

方法

$().alert()

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

.alert('close')

关闭某个警告框。

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

事件

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

EventDescription
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).
  1. $('#my-alert').bind('closed', function () {
  2. // do something…
  3. })

按钮 bootstrap-button.js

使用案例

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

Stateful

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

Single toggle

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

Checkbox

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

  1. class="btn-group" data-toggle="buttons-checkbox">
Radio

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

  1. class="btn-group" data-toggle="buttons-radio">

调用方式

Enable buttons via JavaScript:

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

Heads up!  Firefox persists the disabled state across page loads. A workaround for this is to use  .
$().button('reset')

Resets button state - swaps text to original text.

$().button(string)

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

  1. $('.btn').button('complete')

Collapse bootstrap-collapse.js

About

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

* Requires the Transitions plugin to be included.

Example accordion

Using the collapse plugin, we built a simple accordion style widget:

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.
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.
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.
  1. class="accordion" id="accordion2">
  2. class="accordion-group">
  3. class="accordion-heading">
  4. class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2"href="#collapseOne">
  5. Collapsible Group Item #1
  6. id="collapseOne" class="accordion-body collapse in">
  7. class="accordion-inner">
  8. Anim pariatur cliche...
  9. class="accordion-group">
  10. class="accordion-heading">
  11. class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2"href="#collapseTwo">
  12. Collapsible Group Item #2
  13. id="collapseTwo" class="accordion-body collapse">
  14. class="accordion-inner">
  15. Anim pariatur cliche...
  16. ...

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

  1. simple collapsible
  2.  
  3. id="demo" class="collapse in"> 

调用方式

通过data属性

Just add data-toggle="collapse" and a data-target to 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 collapse to 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.

通过JavaScript

Enable manually with:

  1. $(".collapse").collapse()

选项

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

名称 类型 默认值描述
parent selector false If selector then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior)
toggle boolean true Toggles the collapsible element on invocation

方法

.collapse(options)

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

  1. $('#myCollapsible').collapse({
  2. toggle: false
  3. })
.collapse('toggle')

Toggles a collapsible element to shown or hidden.

.collapse('show')

Shows a collapsible element.

.collapse('hide')

Hides a collapsible element.

事件

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

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

轮播(Carousel) bootstrap-carousel.js

轮播案例

下面就是一个轮播组件的案例。




Third Thumbnail label

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

 
  1. id="myCarousel" class="carousel slide">
    1. class="carousel-indicators">
    2. data-target="#myCarousel" data-slide-to="0" class="active">
  2. data-target="#myCarousel" data-slide-to="1">
  3. data-target="#myCarousel" data-slide-to="2">
class="carousel-inner">
class="active item">
class="item">
class="item">
注意! 当使用轮播组件时,请将案例中的图片替换为你需要展示的图片。

调用方式

通过data属性

使用data属性可以很容易的控制轮播的位置。data-slide内可以包含prev 或 next,他们可以改变当前帧。另外,使用data-slide-to可以传递某个帧的下标,例如data-slide-to="2",这样就可以直接跳转到这个指定的帧 -- 下标从0开始计算。

通过JavaScript

手工启动轮播:

  1. $('.carousel').carousel()

选项

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

名称 类型 默认值描述
interval number 5000 在自动轮播过程中,展示每帧所停留的时间。如果是false,轮播不会自动启动。
pause string "hover" 当鼠标在轮播区域内时暂停循环,在区域外时则继续循环。

方法

.carousel(options)

初始化一个带有可选参数object的轮播,并且自动开始循环播放。

  1. $('.carousel').carousel({
  2. interval: 2000
  3. })
.carousel('cycle')

从左向右循环播放。

.carousel('pause')

停止循环播放。

.carousel(number)

循环到指定帧(下标从0开始,类似数组)。

.carousel('prev')

返回到上一帧。

.carousel('next')

下一帧。

事件

Bootstrap的轮播插件对外暴露了两个可被监听的事件。

事件描述
slideslide实例方法被调用时,此事件会被立即触发。
slid 当切换完一帧后触发。

输入提示bootstrap-typeahead.js

案例

简单,易于扩展,可迅速地为表单中的文本输入框创建优雅的输入提示。

  1.  type="text" data-provide="typeahead">

需要设置以阻止浏览器的默认提示菜单遮盖Bootstrap的输入提示下拉菜单。


调用方式

通过data属性

通过添加data属性给页面元素注册输入提示功能,就像上面的案例一样。

通过JavaScript

手动调用输入提示:

  1. $('.typeahead').typeahead()

选项

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

名称 类型 默认值描述
source array, function [ ] 用于查询的数据源。可以是一个字符串数组或是一个函数。函数会接收到两个参数,分别是输入域中的 query值和process回调函数。函数可能会被同步调用,直接返回数据源;或者异步调用,通过process回调函数的唯一一个参数。
items number 8 下拉菜单中显示的最大的条目数。
minLength number 1 触发提示所需的最小字符个数。
matcher function case insensitive 该函数用于决定某个查询是否匹配某个条目。它接受唯一一个参数item,表示当前需要测试的条目。 使用this.query引用当前查询字符串。如果匹配查询,就返回一个布尔值true 。
sorter function exact match,
case sensitive,
case insensitive
该函数用来排序提示项。它接受唯一一个参数items,并且其变量范围在typeahead实例内。使用this.query引用当前查询字符串。
updater function returns selected item 此方法用于返回选中的条目。其接受一个参数item,并且其变量范围在typeahead实例内。
highlighter function highlights all default matches 该函数用来高亮自动完成的结果。 它接受唯一一个参数item,并且变量范围在typeahead实例内。应该返回html。

方法

.typeahead(options)

为输入框初始化输入提示功能。

附加导航(Affix) bootstrap-affix.js

案例

本页面左侧就是一个附加导航的实际案例。


调用方式

通过data属性

只需添加data-spy="affix"到任意需要监听的页面元素上,就可以很容易的将其变为附加导航。然后使用偏移量来控制其位置。

  1. data-spy="affix" data-offset-top="200">...
Heads up! You must manage the position of a pinned element and the behavior of its immediate parent. Position is controlled by  affixaffix-top, and  affix-bottom. Remember to check for a potentially collapsed parent when the affix kicks in as it's removing content from the normal flow of the page.

通过JavaScript

通过JavaScript启动:

  1. $('#navbar').affix()

选项

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

名称 类型 默认值描述
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 left directions. To listen for a single direction, or multiple unique offsets, just provide an object offset: { x: 10 }. Use a function when you need to dynamically provide an offset (useful for some responsive designs).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值