概览

单独文件或编译文件

插件可以单独包含(使用 Bootstrap 的单独 *.js 文件),或一次性包含所有插件(使用 bootstrap.js 或压缩版 bootstrap.min.js)。

使用编译后的 JavaScript

bootstrap.jsbootstrap.min.js 都在单个文件中包含所有插件。请只包含其中一个。

插件依赖关系

一些插件和 CSS 组件依赖于其他插件。如果您单独包含插件,请确保在文档中检查这些依赖关系。另请注意,所有插件都依赖于 jQuery(这意味着 jQuery 必须在插件文件 之前 包含)。请参考我们的 bower.json 以查看支持哪些版本的 jQuery。

数据属性

您可以纯粹通过标记 API 使用所有 Bootstrap 插件,无需编写一行 JavaScript 代码。这是 Bootstrap 的一等 API,在使用插件时应首先考虑。

话虽如此,在某些情况下可能需要关闭此功能。因此,我们还提供了通过解绑文档上所有命名为 data-api 的事件来禁用数据属性 API 的能力。代码如下:

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

或者,要针对特定插件,只需将插件名称作为命名空间与 data-api 命名空间一起包含,如下所示:

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

每个元素通过数据属性只能使用一个插件

不要在同一个元素上使用来自多个插件的数据属性。例如,一个按钮不能同时有工具提示和切换模态框。要实现这一点,请使用包装元素。

编程式 API

我们还认为您应该能够纯粹通过 JavaScript API 使用所有 Bootstrap 插件。所有公共 API 都是单个、可链式调用的方法,并返回被操作的集合。

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

所有方法应接受一个可选的选项对象、一个目标特定方法的字符串,或不接受任何参数(这将使用默认行为初始化插件):

$('#myModal').modal()                      // 使用默认值初始化
$('#myModal').modal({ keyboard: false })   // 初始化时禁用键盘
$('#myModal').modal('show')                // 初始化并立即调用 show

每个插件还在 Constructor 属性上暴露其原始构造函数:$.fn.popover.Constructor。如果您想获取特定的插件实例,可以直接从元素中检索它:$('[rel="popover"]').data('popover')

默认设置

您可以通过修改插件的 Constructor.DEFAULTS 对象来更改插件的默认设置:

$.fn.modal.Constructor.DEFAULTS.keyboard = false // 将模态框插件的 `keyboard` 选项的默认值更改为 false

无冲突

有时需要将 Bootstrap 插件与其他 UI 框架一起使用。在这些情况下,有时会发生命名空间冲突。如果发生这种情况,您可以对希望恢复其值的插件调用 .noConflict

var bootstrapButton = $.fn.button.noConflict() // 将 $.fn.button 恢复为之前分配的值
$.fn.bootstrapBtn = bootstrapButton            // 为 $().bootstrapBtn 赋予 Bootstrap 功能

事件

Bootstrap 为大多数插件的独特操作提供自定义事件。通常,这些事件以不定式和过去分词形式出现 - 其中不定式形式(例如 show)在事件开始时触发,其过去分词形式(例如 shown)在操作完成时触发。

从 3.0.0 开始,所有 Bootstrap 事件都有命名空间。

所有不定式事件都提供 preventDefault 功能。这提供了在操作开始之前停止其执行的能力。

$('#myModal').on('show.bs.modal', function (e) {
  if (!data) return e.preventDefault() // 阻止模态框显示
})

净化器

工具提示和弹出框使用我们内置的净化器来净化接受 HTML 的选项。

默认的 whiteList 值如下:

var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
var DefaultWhitelist = {
  // 以下任何提供的元素上允许的全局属性。
  '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],
  a: ['target', 'href', 'title', 'rel'],
  area: [],
  b: [],
  br: [],
  col: [],
  code: [],
  div: [],
  em: [],
  hr: [],
  h1: [],
  h2: [],
  h3: [],
  h4: [],
  h5: [],
  h6: [],
  i: [],
  img: ['src', 'alt', 'title', 'width', 'height'],
  li: [],
  ol: [],
  p: [],
  pre: [],
  s: [],
  small: [],
  span: [],
  sub: [],
  sup: [],
  strong: [],
  u: [],
  ul: []
}

如果您想向此默认 whiteList 添加新值,可以执行以下操作:

var myDefaultWhiteList = $.fn.tooltip.Constructor.DEFAULTS.whiteList

// 允许 table 元素
myDefaultWhiteList.table = []

// 允许 td 元素和 td 元素上的 data-option 属性
myDefaultWhiteList.td = ['data-option']

// 您可以推送自定义正则表达式来验证您的属性。
// 请注意您的正则表达式不要太宽松
var myCustomRegex = /^data-my-app-[\w-]+/
myDefaultWhiteList['*'].push(myCustomRegex)

如果您想绕过我们的净化器,因为您更喜欢使用专用库,例如 DOMPurify,您应该执行以下操作:

$('#yourTooltip').tooltip({
  sanitizeFn: function (content) {
    return DOMPurify.sanitize(content)
  }
})

不支持 document.implementation.createHTMLDocument 的浏览器

对于不支持 document.implementation.createHTMLDocument 的浏览器,如 Internet Explorer 8,内置的净化函数会按原样返回 HTML。

如果您想在这种情况下执行净化,请指定 sanitizeFn 并使用外部库,如 DOMPurify

版本号

每个 Bootstrap jQuery 插件的版本都可以通过插件构造函数的 VERSION 属性访问。例如,对于工具提示插件:

$.fn.tooltip.Constructor.VERSION // => "3.4.1"

JavaScript 被禁用时无特殊回退

当 JavaScript 被禁用时,Bootstrap 的插件不会特别优雅地回退。如果您关心这种情况下的用户体验,请使用 <noscript> 向您的用户解释情况(以及如何重新启用 JavaScript),和/或添加您自己的自定义回退。

第三方库

Bootstrap 官方不支持第三方 JavaScript 库,如 Prototype 或 jQuery UI。尽管有 .noConflict 和命名空间事件,可能仍会有兼容性问题需要您自己修复。

过渡效果 transition.js

关于过渡效果

对于简单的过渡效果,请在其他 JS 文件旁边包含一次 transition.js。如果您使用的是编译后的(或压缩的)bootstrap.js,则无需包含此文件—它已经在其中了。

包含内容

Transition.js 是 transitionEnd 事件的基本辅助工具,也是 CSS 过渡效果的模拟器。它被其他插件用来检查 CSS 过渡支持并捕获挂起的过渡。

禁用过渡效果

可以使用以下 JavaScript 代码片段全局禁用过渡效果,该代码片段必须在加载 transition.js(或 bootstrap.jsbootstrap.min.js,视情况而定)之后出现:

$.support.transition = false

模态框 modal.js

模态框是流线型但灵活的对话框提示,具有最少的必要功能和智能默认值。

不支持多个打开的模态框

确保在另一个模态框仍可见时不要打开新的模态框。同时显示多个模态框需要自定义代码。

模态框标记放置

始终尝试将模态框的 HTML 代码放置在文档的顶层位置,以避免其他组件影响模态框的外观和/或功能。

移动设备注意事项

在移动设备上使用模态框有一些注意事项。请参阅我们的浏览器支持文档了解详细信息。

由于 HTML5 定义其语义的方式,autofocus HTML 属性在 Bootstrap 模态框中不起作用。要实现相同的效果,请使用一些自定义 JavaScript:

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})

示例

静态示例

一个带有标题、正文和页脚操作集的渲染模态框。

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="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">关闭</button>
        <button type="button" class="btn btn-primary">保存更改</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

实时演示

通过点击下面的按钮,使用 JavaScript 切换模态框。它将从页面顶部滑下并淡入。

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  启动演示模态框
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">模态框标题</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary">保存更改</button>
      </div>
    </div>
  </div>
</div>

使模态框可访问

确保向 .modal 添加 role="dialog"aria-labelledby="..."(引用模态框标题),并向 .modal-dialog 本身添加 role="document"

此外,您可以在 .modal 上使用 aria-describedby 为模态对话框提供描述。

嵌入 YouTube 视频

在模态框中嵌入 YouTube 视频需要 Bootstrap 中没有的额外 JavaScript,以自动停止播放等。请参阅这个有用的 Stack Overflow 帖子了解更多信息。

可选尺寸

模态框有两种可选尺寸,可通过放置在 .modal-dialog 上的修饰符类获得。

<!-- Large modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">大型模态框</button>

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog modal-lg" role="document">
    <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">小型模态框</button>

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      ...
    </div>
  </div>
</div>

移除动画

对于简单出现而不是淡入视图的模态框,从模态框标记中移除 .fade 类。

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

使用网格系统

要在模态框中利用 Bootstrap 网格系统,只需在 .modal-body 中嵌套 .row,然后使用正常的网格系统类。

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="gridSystemModalLabel">模态框标题</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-4">.col-md-4</div>
          <div class="col-md-4 col-md-offset-4">.col-md-4 .col-md-offset-4</div>
        </div>
        <div class="row">
          <div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div>
          <div class="col-md-2 col-md-offset-4">.col-md-2 .col-md-offset-4</div>
        </div>
        <div class="row">
          <div class="col-md-6 col-md-offset-3">.col-md-6 .col-md-offset-3</div>
        </div>
        <div class="row">
          <div class="col-sm-9">
            Level 1: .col-sm-9
            <div class="row">
              <div class="col-xs-8 col-sm-6">
                Level 2: .col-xs-8 .col-sm-6
              </div>
              <div class="col-xs-4 col-sm-6">
                Level 2: .col-xs-4 .col-sm-6
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary">保存更改</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

有一堆按钮都触发同一个模态框,只是内容略有不同?使用 event.relatedTargetHTML data-* 属性(可能 通过 jQuery)根据点击的按钮来改变模态框的内容。有关 relatedTarget 的详细信息,请参阅模态框事件文档。

...more buttons...
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">为 @mdo 打开模态框</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@fat">为 @fat 打开模态框</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">为 @getbootstrap 打开模态框</button>
...more buttons...

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">新消息</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="recipient-name" class="control-label">收件人:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="form-group">
            <label for="message-text" class="control-label">消息:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary">发送消息</button>
      </div>
    </div>
  </div>
</div>
$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

使用方法

模态框插件通过数据属性或 JavaScript 按需切换您的隐藏内容。它还向 <body> 添加 .modal-open 以覆盖默认滚动行为,并生成 .modal-backdrop 以提供点击区域,当点击模态框外部时关闭显示的模态框。

通过数据属性

无需编写 JavaScript 即可激活模态框。在控制器元素(如按钮)上设置 data-toggle="modal",并使用 data-target="#foo"href="#foo" 来目标特定的模态框进行切换。

<button type="button" data-toggle="modal" data-target="#myModal">启动模态框</button>

通过 JavaScript

使用一行 JavaScript 调用 id 为 myModal 的模态框:

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

选项

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-backdrop=""

名称 类型 默认值 描述
backdrop boolean or the string 'static' true 包含模态框背景元素。或者,指定 static 用于点击时不关闭模态框的背景。
keyboard boolean true 按 Esc 键关闭模态框
show boolean true 初始化时显示模态框。
remote path false

此选项自 v3.3.0 起已弃用,并在 v4 中已移除。我们建议改用客户端模板或数据绑定框架,或自己调用 jQuery.load

如果提供了远程 URL,内容将通过 jQuery 的 load 方法加载一次并注入到 .modal-content div 中。如果您使用数据 API,您也可以使用 href 属性指定远程源。下面显示了一个示例:

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

方法

.modal(options)

激活您的内容作为模态框。接受一个可选的选项 object

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

.modal('toggle')

手动切换模态框。在模态框实际显示或隐藏之前返回给调用者(即,在 shown.bs.modalhidden.bs.modal 事件发生之前)。

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

.modal('show')

手动打开模态框。在模态框实际显示之前返回给调用者(即,在 shown.bs.modal 事件发生之前)。

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

.modal('hide')

手动隐藏模态框。在模态框实际隐藏之前返回给调用者(即,在 hidden.bs.modal 事件发生之前)。

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

.modal('handleUpdate')

重新调整模态框的定位以抵消滚动条,以防滚动条出现,这会使模态框向左跳动。

仅当模态框的高度在打开时发生变化时才需要。

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

事件

Bootstrap 的模态框类公开了一些事件,用于挂钩到模态框功能中。

所有模态框事件都在模态框本身(即 <div class="modal">)上触发。

事件类型 描述
show.bs.modal 当调用 show 实例方法时,此事件立即触发。如果由点击引起,则点击的元素可作为事件的 relatedTarget 属性使用。
shown.bs.modal 当模态框对用户可见时触发此事件(将等待 CSS 过渡完成)。如果由点击引起,则点击的元素可作为事件的 relatedTarget 属性使用。
hide.bs.modal 当调用 hide 实例方法时,此事件立即触发。
hidden.bs.modal 当模态框完成隐藏时触发此事件(将等待 CSS 过渡完成)。
loaded.bs.modal 当模态框使用 remote 选项加载内容时触发此事件。
$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

下拉菜单 dropdown.js

使用这个简单的插件,可以向下拉菜单添加几乎任何内容,包括导航栏、标签页和胶囊式导航。

在导航栏中

在胶囊式导航中

通过数据属性或 JavaScript,下拉菜单插件通过在父列表项上切换 .open 类来切换隐藏内容(下拉菜单)。

在移动设备上,打开下拉菜单会添加一个 .dropdown-backdrop 作为点击区域,用于在点击菜单外部时关闭下拉菜单,这是 iOS 支持所必需的。这意味着在移动设备上,从一个打开的下拉菜单切换到另一个下拉菜单需要额外的点击。

注意:data-toggle="dropdown" 属性在应用程序级别用于关闭下拉菜单,因此始终使用它是个好主意。

通过数据属性

向链接或按钮添加 data-toggle="dropdown" 以切换下拉菜单。

<div class="dropdown">
  <button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    下拉菜单触发器
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dLabel">
    ...
  </ul>
</div>

要保持链接按钮的 URL 完整,请使用 data-target 属性而不是 href="#"

<div class="dropdown">
  <a id="dLabel" data-target="#" href="http://example.com/" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
    下拉菜单触发器
    <span class="caret"></span>
  </a>

  <ul class="dropdown-menu" aria-labelledby="dLabel">
    ...
  </ul>
</div>

通过 JavaScript

通过 JavaScript 调用下拉菜单:

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

仍然需要 data-toggle="dropdown"

无论您是通过 JavaScript 调用下拉菜单还是使用数据 API,data-toggle="dropdown" 始终需要存在于下拉菜单的触发元素上。

$().dropdown('toggle')

切换给定导航栏或标签式导航的下拉菜单。

所有下拉菜单事件都在 .dropdown-menu 的父元素上触发。

所有下拉菜单事件都有一个 relatedTarget 属性,其值是触发锚点元素。

事件类型 描述
show.bs.dropdown 当调用 show 实例方法时,此事件立即触发。
shown.bs.dropdown 当下拉菜单对用户可见时触发此事件(将等待 CSS 过渡完成)。
hide.bs.dropdown 当调用 hide 实例方法时,此事件立即触发。
hidden.bs.dropdown 当下拉菜单完成隐藏时触发此事件(将等待 CSS 过渡完成)。
$('#myDropdown').on('show.bs.dropdown', function () {
  // do something…
})

滚动监听 scrollspy.js

导航栏中的示例

滚动监听插件用于根据滚动位置自动更新导航目标。滚动导航栏下方的区域,观察活动类的变化。下拉子项也会被高亮显示。

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

使用方法

需要 Bootstrap 导航

滚动监听目前需要使用 Bootstrap 导航组件 来正确高亮活动链接。

需要可解析的 ID 目标

导航栏链接必须有可解析的 id 目标。例如,<a href="#home">home</a> 必须对应 DOM 中的某个元素,如 <div id="home"></div>

忽略非 :visible 目标元素

根据 jQuery 不是 :visible 的目标元素将被忽略,它们对应的导航项永远不会被高亮。

需要相对定位

无论实现方法如何,滚动监听都需要在您要监听的元素上使用 position: relative;。在大多数情况下,这是 <body>。当在 <body> 以外的元素上进行滚动监听时,确保设置了 height 并应用了 overflow-y: scroll;

通过数据属性

要轻松地向顶栏导航添加滚动监听行为,向要监听的元素(最典型的是 <body>)添加 data-spy="scroll"。然后添加 data-target 属性,其值为任何 Bootstrap .nav 组件的父元素的 ID 或类。

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

通过 JavaScript

在 CSS 中添加 position: relative; 后,通过 JavaScript 调用滚动监听:

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

方法

.scrollspy('refresh')

当使用滚动监听并同时从 DOM 中添加或删除元素时,您需要调用 refresh 方法:

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

选项

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-offset=""

名称 类型 默认值 描述
offset number 10 计算滚动位置时从顶部偏移的像素数。

事件

事件类型 描述
activate.bs.scrollspy 当滚动监听激活新项目时,此事件触发。
$('#myScrollspy').on('activate.bs.scrollspy', function () {
  // do something…
})

可切换标签页 tab.js

标签页示例

添加快速、动态的标签页功能,用于在本地内容面板之间切换,甚至可以通过下拉菜单进行切换。不支持嵌套标签页。

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.

扩展标签导航

此插件扩展了 标签导航组件,添加了可切换的内容区域。

使用方法

通过 JavaScript 启用可切换标签页(每个标签页需要单独激活):

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

您可以通过多种方式激活单个标签页:

$('#myTabs a[href="#profile"]').tab('show') // 通过名称选择标签页
$('#myTabs a:first').tab('show') // 选择第一个标签页
$('#myTabs a:last').tab('show') // 选择最后一个标签页
$('#myTabs li:eq(2) a').tab('show') // 选择第三个标签页(从0开始索引)

标记

您可以无需编写任何 JavaScript 即可激活标签页或胶囊式导航,只需在元素上指定 data-toggle="tab"data-toggle="pill"。向标签页 ul 添加 navnav-tabs 类将应用 Bootstrap 标签样式,而添加 navnav-pills 类将应用 胶囊式样式

<div>

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
    <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
    <li role="presentation"><a href="#settings" aria-controls="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>

</div>

淡入效果

要使标签页淡入显示,请为每个 .tab-pane 添加 .fade 类。第一个标签页面板还必须具有 .in 类,以使初始内容可见。

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

方法

$().tab

激活标签页元素和内容容器。标签页应该具有 data-targethref 属性,指向 DOM 中的容器节点。在上面的示例中,标签页是带有 data-toggle="tab" 属性的 <a> 元素。

.tab('show')

选择给定的标签页并显示其关联的内容。之前选择的任何其他标签页将变为未选择状态,其关联的内容将被隐藏。在标签页面板实际显示之前(即 shown.bs.tab 事件发生之前)返回给调用者

$('#someTab').tab('show')

事件

显示新标签页时,事件按以下顺序触发:

  1. hide.bs.tab(在当前活动标签页上)
  2. show.bs.tab(在将要显示的标签页上)
  3. hidden.bs.tab(在之前活动的标签页上,与 hide.bs.tab 事件相同的标签页)
  4. shown.bs.tab(在新激活的刚刚显示的标签页上,与 show.bs.tab 事件相同的标签页)

如果没有标签页已经激活,则不会触发 hide.bs.tabhidden.bs.tab 事件。

事件类型 描述
show.bs.tab 此事件在标签页显示时触发,但在新标签页实际显示之前。使用 event.targetevent.relatedTarget 分别定位活动标签页和之前的活动标签页(如果可用)。
shown.bs.tab 此事件在标签页显示后触发。使用 event.targetevent.relatedTarget 分别定位活动标签页和之前的活动标签页(如果可用)。
hide.bs.tab 此事件在将要显示新标签页时触发(因此之前的活动标签页将被隐藏)。使用 event.targetevent.relatedTarget 分别定位当前活动标签页和即将激活的新标签页。
hidden.bs.tab 此事件在新标签页显示后触发(因此之前的活动标签页被隐藏)。使用 event.targetevent.relatedTarget 分别定位之前的活动标签页和新的活动标签页。
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  e.target // 新激活的标签页
  e.relatedTarget // 之前的活动标签页
})

提示工具 tooltip.js

灵感来源于 Jason Frame 编写的优秀 jQuery.tipsy 插件;提示工具是其更新版本,不依赖图像,使用 CSS3 进行动画,并使用数据属性存储本地标题。

标题长度为零的提示工具永远不会显示。

示例

将鼠标悬停在下面的链接上查看提示工具:

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.

静态提示工具

有四种选项可用:顶部、右侧、底部和左侧对齐。

四个方向

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left">左侧的提示工具</button>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">顶部的提示工具</button>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom">底部的提示工具</button>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right">右侧的提示工具</button>

选择性启用功能

出于性能原因,提示工具和弹出框的数据 API 是选择性启用的,这意味着 您必须自行初始化它们

初始化页面上所有提示工具的一种方法是通过它们的 data-toggle 属性选择它们:

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

使用方法

提示工具插件根据需要生成内容和标记,默认情况下将提示工具放置在其触发元素之后。

通过 JavaScript 触发提示工具:

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

标记

提示工具所需的标记只是您希望具有提示工具的 HTML 元素上的 data 属性和 title。提示工具生成的标记相当简单,尽管它确实需要一个位置(默认情况下,由插件设置为 top)。

<!-- HTML 代码 -->
<a href="#" data-toggle="tooltip" title="一些提示工具文本!">悬停在我上面</a>

<!-- 插件生成的标记 -->
<div class="tooltip top" role="tooltip">
  <div class="tooltip-arrow"></div>
  <div class="tooltip-inner">
    一些提示工具文本!
  </div>
</div>

多行链接

有时您想为换行的超链接添加提示工具。提示工具插件的默认行为是将其水平和垂直居中。向您的锚点添加 white-space: nowrap; 以避免这种情况。

按钮组、输入组和表格中的提示工具需要特殊设置

.btn-group.input-group 内的元素上使用提示工具,或在表格相关元素(<td><th><tr><thead><tbody><tfoot>)上使用时,您必须指定选项 container: 'body'(如下所述)以避免不必要的副作用(例如,当触发提示工具时元素变宽和/或失去其圆角)。

不要尝试在隐藏元素上显示提示工具

当目标元素为 display: none; 时调用 $(...).tooltip('show') 会导致提示工具定位不正确。

为键盘和辅助技术用户提供可访问的提示工具

对于使用键盘导航的用户,尤其是辅助技术的用户,您应该只向键盘可聚焦元素添加提示工具,例如链接、表单控件或任何带有 tabindex="0" 属性的任意元素。

禁用元素上的提示工具需要包装元素

要向 disabled.disabled 元素添加提示工具,请将该元素放在 <div> 内,并将提示工具应用于该 <div>

选项

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-animation=""

请注意,出于安全原因,sanitizesanitizeFnwhiteList 选项不能使用数据属性提供。

名称 类型 默认值 描述
animation boolean true 为提示工具应用 CSS 淡入过渡效果
container string | false false

将提示工具附加到特定元素。示例:container: 'body'。此选项特别有用,因为它允许您在文档流中靠近触发元素的位置定位提示工具 - 这将防止提示工具在窗口调整大小时远离触发元素。

delay number | object 0

延迟显示和隐藏提示工具(毫秒)- 不适用于手动触发类型

如果提供数字,则延迟应用于显示和隐藏

对象结构为:delay: { "show": 500, "hide": 100 }

html boolean false 将 HTML 插入到提示工具中。如果为 false,将使用 jQuery 的 text 方法将内容插入到 DOM 中。如果担心 XSS 攻击,请使用 text。
placement string | function 'top'

如何定位提示工具 - top | bottom | left | right | auto。
当指定 "auto" 时,它将动态调整提示工具的方向。例如,如果 placement 为 "auto left",则提示工具将尽可能显示在左侧,否则将显示在右侧。

当使用函数确定放置位置时,它会以提示工具 DOM 节点作为第一个参数,触发元素 DOM 节点作为第二个参数被调用。this 上下文设置为提示工具实例。

selector string false 如果提供了选择器,提示工具对象将被委托给指定的目标。实际上,这用于将提示工具应用于动态添加的 DOM 元素(支持 jQuery.on)。请参阅 此问题一个信息性示例
template string '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'

创建提示工具时使用的基本 HTML。

提示工具的 title 将被注入到 .tooltip-inner 中。

.tooltip-arrow 将成为提示工具的箭头。

最外层的包装元素应该具有 .tooltip 类。

title string | function ''

如果 title 属性不存在,则使用默认标题值。

如果给定函数,它将被调用,其 this 引用设置为提示工具所附加的元素。

trigger string 'hover focus' 提示工具的触发方式 - click | hover | focus | manual。您可以传递多个触发器;用空格分隔它们。manual 不能与任何其他触发器组合。
viewport string | object | function { selector: 'body', padding: 0 }

使提示工具保持在该元素的边界内。示例:viewport: '#viewport'{ "selector": "#viewport", "padding": 0 }

如果给定函数,它会以触发元素 DOM 节点作为其唯一参数被调用。this 上下文设置为提示工具实例。

sanitize boolean true 启用或禁用清理。如果激活,'template''content''title' 选项将被清理。
whiteList object 默认值 包含允许的属性和标签的对象
sanitizeFn null | function null 您可以在此处提供自己的清理函数。如果您更喜欢使用专用库执行清理,这会很有用。

单个提示工具的数据属性

单个提示工具的选项也可以通过使用数据属性来指定,如上所述。

方法

$().tooltip(options)

将提示工具处理程序附加到元素集合。

.tooltip('show')

显示元素的提示工具。在提示工具实际显示之前(即 shown.bs.tooltip 事件发生之前)返回给调用者。这被视为提示工具的“手动”触发。标题长度为零的提示工具永远不会显示。

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

.tooltip('hide')

隐藏元素的提示工具。在提示工具实际隐藏之前(即 hidden.bs.tooltip 事件发生之前)返回给调用者。这被视为提示工具的“手动”触发。

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

.tooltip('toggle')

切换元素的提示工具。在提示工具实际显示或隐藏之前(即 shown.bs.tooltiphidden.bs.tooltip 事件发生之前)返回给调用者。这被视为提示工具的“手动”触发。

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

.tooltip('destroy')

隐藏并销毁元素的提示工具。使用委托创建的提示工具(使用 selector 选项 创建)不能在后代触发元素上单独销毁。

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

事件

事件类型 描述
show.bs.tooltip 当调用 show 实例方法时,此事件立即触发。
shown.bs.tooltip 当提示工具对用户可见时触发此事件(将等待 CSS 过渡完成)。
hide.bs.tooltip 当调用 hide 实例方法时,此事件立即触发。
hidden.bs.tooltip 当提示工具完成对用户的隐藏时触发此事件(将等待 CSS 过渡完成)。
inserted.bs.tooltip 当提示工具模板添加到 DOM 后,在 show.bs.tooltip 事件之后触发此事件。
$('#myTooltip').on('hidden.bs.tooltip', function () {
  // 执行某些操作…
})

弹出框 popover.js

向任何元素添加小型内容覆盖层,如 iPad 上的那些,用于容纳次要信息。

标题和内容均为零长度的弹出框永远不会显示。

插件依赖

弹出框需要在您的 Bootstrap 版本中包含 工具提示插件

选择加入功能

出于性能原因,Tooltip 和 Popover 数据 API 是选择加入的,这意味着 您必须自己初始化它们

初始化页面上所有弹出框的一种方法是通过它们的 data-toggle 属性选择它们:

$(function () {
  $('[data-toggle="popover"]').popover()
})

按钮组、输入组和表格中的弹出框需要特殊设置

.btn-group.input-group 内的元素上使用弹出框,或在表格相关元素(<td><th><tr><thead><tbody><tfoot>)上使用弹出框时,您必须指定选项 container: 'body'(下面有文档)以避免不必要的副作用(例如,当弹出框被触发时,元素变宽和/或失去圆角)。

不要尝试在隐藏元素上显示弹出框

当目标元素为 display: none; 时调用 $(...).popover('show') 会导致弹出框定位不正确。

禁用元素上的弹出框需要包装元素

要向 disabled.disabled 元素添加弹出框,请将该元素放在 <div> 内,并将弹出框应用于该 <div> 而不是元素本身。

多行链接

有时您想向换行的超链接添加弹出框。弹出框插件的默认行为是水平和垂直居中它。向您的锚点添加 white-space: nowrap; 以避免这种情况。

示例

静态弹出框

有四个选项可用:顶部、右侧、底部和左侧对齐。

顶部弹出框

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

右侧弹出框

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

底部弹出框

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

左侧弹出框

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

实时演示

<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="弹出框标题" data-content="这里有一些惊人的内容。非常吸引人,对吧?">点击切换弹出框</button>

四个方向

<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.">
  左侧弹出框
</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.">
  顶部弹出框
</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.">
  底部弹出框
</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.">
  右侧弹出框
</button>

下次点击时关闭

使用 focus 触发器在用户下次点击时关闭弹出框。

下次点击关闭需要特定标记

为了获得正确的跨浏览器和跨平台行为,您必须使用 <a> 标签,而不是 <button> 标签,并且您还必须包含 role="button"tabindex 属性。

<a tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="可关闭的弹出框" data-content="这里有一些惊人的内容。非常吸引人,对吧?">可关闭的弹出框</a>

使用方法

通过 JavaScript 启用弹出框:

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

选项

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-animation=""

请注意,出于安全原因,sanitizesanitizeFnwhiteList 选项不能使用数据属性提供。

名称 类型 默认值 描述
animation boolean true 对弹出框应用 CSS 淡入过渡
container string | false false

将弹出框附加到特定元素。示例:container: 'body'。此选项特别有用,因为它允许您将弹出框定位在文档流中靠近触发元素的位置 - 这将防止弹出框在窗口调整大小时漂浮远离触发元素。

content string | function ''

如果 data-content 属性不存在,则为默认内容值。

如果提供了函数,它将被调用,其 this 引用设置为弹出框所附加的元素。

delay number | object 0

延迟显示和隐藏弹出框(毫秒)- 不适用于手动触发类型

如果提供了数字,延迟将应用于显示和隐藏

对象结构为:delay: { "show": 500, "hide": 100 }

html boolean false 在弹出框中插入 HTML。如果为 false,将使用 jQuery 的 text 方法将内容插入到 DOM 中。如果您担心 XSS 攻击,请使用 text。
placement string | function 'right'

如何定位弹出框 - top | bottom | left | right | auto。
当指定 "auto" 时,它将动态重新定位弹出框。例如,如果 placement 是 "auto left",弹出框将在可能的情况下显示在左侧,否则将显示在右侧。

当使用函数来确定放置位置时,它会被调用,第一个参数是弹出框 DOM 节点,第二个参数是触发元素 DOM 节点。this 上下文设置为弹出框实例。

selector string false 如果提供了选择器,弹出框对象将被委托给指定的目标。在实践中,这用于使动态 HTML 内容能够添加弹出框。请参阅 一个信息丰富的示例
template string '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'

创建弹出框时使用的基础 HTML。

弹出框的 title 将被注入到 .popover-title 中。

弹出框的 content 将被注入到 .popover-content 中。

.arrow 将成为弹出框的箭头。

最外层的包装元素应该有 .popover 类。

title string | function ''

如果 title 属性不存在,则为默认标题值。

如果提供了函数,它将被调用,其 this 引用设置为弹出框所附加的元素。

trigger string 'click' 弹出框如何触发 - click | hover | focus | manual。您可以传递多个触发器;用空格分隔它们。manual 不能与任何其他触发器组合。
viewport string | object | function { selector: 'body', padding: 0 }

保持弹出框在该元素的边界内。示例:viewport: '#viewport'{ "selector": "#viewport", "padding": 0 }

如果提供了函数,它将被调用,唯一的参数是触发元素 DOM 节点。this 上下文设置为弹出框实例。

sanitize boolean true 启用或禁用 sanitization。如果激活,'template''content''title' 选项将被 sanitize。
whiteList object 默认值 包含允许的属性和标签的对象
sanitizeFn null | function null 您可以在这里提供自己的 sanitize 函数。如果您更喜欢使用专用库来执行 sanitization,这会很有用。

单个弹出框的数据属性

单个弹出框的选项也可以通过使用数据属性来指定,如上所述。

方法

$().popover(options)

初始化元素集合的弹出框。

.popover('show')

显示元素的弹出框。在弹出框实际显示之前返回给调用者(即,在 shown.bs.popover 事件发生之前)。这被视为弹出框的"手动"触发。标题和内容均为零长度的弹出框永远不会显示。

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

.popover('hide')

隐藏元素的弹出框。在弹出框实际隐藏之前返回给调用者(即,在 hidden.bs.popover 事件发生之前)。这被视为弹出框的"手动"触发。

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

.popover('toggle')

切换元素的弹出框。在弹出框实际显示或隐藏之前返回给调用者(即,在 shown.bs.popoverhidden.bs.popover 事件发生之前)。这被视为弹出框的"手动"触发。

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

.popover('destroy')

.popover('destroy')

隐藏并销毁元素的弹出框。使用委托的弹出框(使用 selector 选项 创建的)不能在后代触发元素上单独销毁。

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

事件

事件类型 描述
show.bs.popover 当调用 show 实例方法时,此事件立即触发。
shown.bs.popover 当弹出框对用户可见时触发此事件(将等待 CSS 过渡完成)。
hide.bs.popover 当调用 hide 实例方法时,此事件立即触发。
hidden.bs.popover 当弹出框完成隐藏时触发此事件(将等待 CSS 过渡完成)。
inserted.bs.popover 当弹出框模板已添加到 DOM 后,此事件在 show.bs.popover 事件之后触发。
$('#myPopover').on('hidden.bs.popover', function () {
  // do something…
})

警告框消息 alert.js

警告框示例

使用此插件为所有警告框消息添加关闭功能。

当使用 .close 按钮时,它必须是 .alert-dismissible 的第一个子元素,并且在标记中它前面不能有任何文本内容。

使用方法

只需在关闭按钮上添加 data-dismiss="alert",即可自动为警告框提供关闭功能。关闭警告框会将其从 DOM 中移除。

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

要让您的警告框在关闭时使用动画,请确保它们已经应用了 .fade.in 类。

方法

$().alert()

使警告框监听具有 data-dismiss="alert" 属性的后代元素上的点击事件。(使用 data-api 的自动初始化时不需要。)

$().alert('close')

通过从 DOM 中移除警告框来关闭它。如果元素上存在 .fade.in 类,警告框将在被移除前淡出。

事件

Bootstrap 的警告框插件暴露了几个事件,用于挂钩到警告框功能。

事件类型 描述
close.bs.alert 当调用 close 实例方法时,此事件立即触发。
closed.bs.alert 当警告框已关闭时触发此事件(将等待 CSS 过渡完成)。
$('#myAlert').on('closed.bs.alert', function () {
  // 执行某些操作…
})

按钮 button.js

让按钮发挥更多作用。控制按钮状态或创建按钮组以构建更多组件,如工具栏。

跨浏览器兼容性

Firefox 在页面加载之间会保留表单控件状态(禁用状态和选中状态)。解决此问题的方法是使用 autocomplete="off"。请参阅 Mozilla bug #654072

有状态

添加 data-loading-text="Loading..." 以在按钮上使用加载状态。

此功能自 v3.3.5 起已被弃用,并在 v4 中被移除。

使用您喜欢的任何状态!

为了演示,我们使用 data-loading-text$().button('loading'),但这不是您可以使用的唯一状态。在下面的 $().button(string) 文档中查看更多信息

<button type="button" id="myButton" data-loading-text="Loading..." class="btn btn-primary">
  加载状态
</button>

<script>
  $('#myButton').on('click', function () {
    var $btn = $(this).button('loading')
    // 业务逻辑...
    $btn.button('reset')
  })
</script>

单一切换

添加 data-toggle="button" 以在单个按钮上激活切换功能。

预切换的按钮需要 .activearia-pressed="true"

对于预切换的按钮,您必须自己向 button 添加 .active 类和 aria-pressed="true" 属性。

<button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false">
  单一切换
</button>

复选框 / 单选按钮

向包含复选框或单选按钮输入的 .btn-group 添加 data-toggle="buttons",以在其各自的样式中启用切换。

预选选项需要 .active

对于预选选项,您必须自己向输入的 label 添加 .active 类。

视觉选中状态仅在点击时更新

如果复选框按钮的选中状态在没有触发按钮上的 click 事件的情况下更新(例如,通过 <input type="reset"> 或通过设置输入的 checked 属性),您需要自己在输入的 label 上切换 .active 类。

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> 复选框 1(预选中)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> 复选框 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> 复选框 3
  </label>
</div>
<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" checked> 单选按钮 1(预选)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> 单选按钮 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> 单选按钮 3
  </label>
</div>

方法

$().button('toggle')

切换按下状态。给按钮一种已被激活的外观。

$().button('reset')

重置按钮状态 - 将文本切换回原始文本。此方法是异步的,会在重置实际完成之前返回。

$().button(string)

将文本切换到任何数据定义的文本状态。

<button type="button" id="myStateButton" data-complete-text="完成!" class="btn btn-primary">
  ...
</button>

<script>
  $('#myStateButton').on('click', function () {
    $(this).button('complete') // 按钮文本将变为 "完成!"
  })
</script>

折叠 collapse.js

灵活的插件,利用少量类实现简单的切换行为。

插件依赖

折叠插件需要在您的 Bootstrap 版本中包含 过渡插件

示例

点击下面的按钮,通过类的变化来显示和隐藏另一个元素:

  • .collapse 隐藏内容
  • .collapsing 在过渡期间应用
  • .collapse.in 显示内容

您可以使用带有 href 属性的链接,或带有 data-target 属性的按钮。在两种情况下,都需要 data-toggle="collapse"

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
<a class="btn btn-primary" role="button" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
  带 href 的链接
</a>
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
  带 data-target 的按钮
</button>
<div class="collapse" id="collapseExample">
  <div class="well">
    ...
  </div>
</div>

手风琴示例

扩展默认的折叠行为,使用面板组件创建手风琴。

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.
<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 role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          可折叠组项目 #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" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          可折叠组项目 #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" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          可折叠组项目 #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>

也可以用 .list-group 替换 .panel-body

  • Bootply
  • One itmus ac facilin
  • Second eros

使展开/折叠控件可访问

确保向控制元素添加 aria-expanded。此属性向屏幕阅读器和类似的辅助技术明确定义可折叠元素的当前状态。如果可折叠元素默认关闭,则其值应为 aria-expanded="false"。如果您使用 in 类将可折叠元素设置为默认打开,则应在控件上设置 aria-expanded="true"。插件会根据可折叠元素是否已打开或关闭自动切换此属性。

此外,如果您的控制元素针对单个可折叠元素——即 data-target 属性指向 id 选择器——您可以向控制元素添加额外的 aria-controls 属性,包含可折叠元素的 id。现代屏幕阅读器和类似的辅助技术使用此属性为用户提供额外的快捷方式,直接导航到可折叠元素本身。

使用方法

折叠插件使用几个类来处理繁重的工作:

  • .collapse 隐藏内容
  • .collapse.in 显示内容
  • .collapsing 在过渡开始时添加,在过渡结束时移除

这些类可以在 component-animations.less 中找到。

通过数据属性

只需向元素添加 data-toggle="collapse"data-target,即可自动分配对可折叠元素的控制。data-target 属性接受一个 CSS 选择器,应用于要折叠的元素。确保向可折叠元素添加 collapse 类。如果您希望它默认打开,请添加额外的 in 类。

要向可折叠控件添加手风琴式的组管理,请添加数据属性 data-parent="#selector"。请参考演示来查看实际效果。

通过 JavaScript

手动启用:

$('.collapse').collapse()

选项

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-parent=""

名称 类型 默认值 描述
parent selector false 如果提供了选择器,那么当此可折叠项显示时,指定父元素下的所有可折叠元素都将关闭。(类似于传统手风琴行为 - 这依赖于 panel 类)
toggle boolean true 在调用时切换可折叠元素的状态

方法

.collapse(options)

激活您的内容作为可折叠元素。接受一个可选的选项 object

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

.collapse('toggle')

切换可折叠元素的显示或隐藏状态。在可折叠元素实际显示或隐藏之前返回给调用者(即,在 shown.bs.collapsehidden.bs.collapse 事件发生之前)。

.collapse('show')

显示可折叠元素。在可折叠元素实际显示之前返回给调用者(即,在 shown.bs.collapse 事件发生之前)。

.collapse('hide')

隐藏可折叠元素。在可折叠元素实际隐藏之前返回给调用者(即,在 hidden.bs.collapse 事件发生之前)。

事件

Bootstrap 的折叠类公开了一些事件,用于挂钩到折叠功能中。

事件类型 描述
show.bs.collapse 当调用 show 实例方法时,此事件立即触发。
shown.bs.collapse 当折叠元素对用户可见时触发此事件(将等待 CSS 过渡完成)。
hide.bs.collapse 当调用 hide 方法时,此事件立即触发。
hidden.bs.collapse 当折叠元素对用户隐藏时触发此事件(将等待 CSS 过渡完成)。
$('#myCollapsible').on('hidden.bs.collapse', function () {
  // do something…
})

轮播 carousel.js

一个用于循环浏览元素的幻灯片组件,就像轮播一样。不支持嵌套轮播。

<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" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

可选的标题

通过在任何 .item 中使用 .carousel-caption 元素,可以轻松地为幻灯片添加标题。在其中放置几乎任何可选的 HTML,它都会自动对齐和格式化。

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

多个轮播

轮播需要在最外层容器(.carousel)上使用 id,以便轮播控件正常工作。添加多个轮播或更改轮播的 id 时,请确保更新相关控件。

通过数据属性

使用数据属性可以轻松控制轮播的位置。data-slide 接受关键字 prevnext,它们会相对于当前位置更改幻灯片位置。或者,使用 data-slide-to 向轮播传递原始幻灯片索引,例如 data-slide-to="2",它会将幻灯片位置移动到从 0 开始的特定索引。

data-ride="carousel" 属性用于标记轮播在页面加载时开始动画。它不能与同一轮播的(冗余且不必要的)显式 JavaScript 初始化结合使用。

通过 JavaScript

通过 JavaScript 手动调用轮播:

$('.carousel').carousel()

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-interval=""

名称 类型 默认值 描述
interval number 5000 自动循环项目之间的延迟时间(毫秒)。如果为 false,轮播将不会自动循环。
pause string | null "hover" 如果设置为 "hover",则在鼠标悬停时暂停轮播循环,在鼠标离开时恢复轮播循环。如果设置为 null,悬停在轮播上不会暂停它。
wrap boolean true 轮播是否应该连续循环或有硬停止。
keyboard boolean true 轮播是否应该响应键盘事件。

.carousel(options)

使用可选的选项 object 初始化轮播并开始循环项目。

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

.carousel('cycle')

从左到右循环轮播项目。

.carousel('pause')

停止轮播循环项目。

.carousel(number)

将轮播循环到特定帧(基于 0,类似于数组)。

.carousel('prev')

循环到上一个项目。

.carousel('next')

循环到下一个项目。

Bootstrap 的轮播类公开了两个事件,用于挂钩到轮播功能中。

这两个事件都有以下附加属性:

  • direction:轮播滑动的方向("left""right")。
  • relatedTarget:作为活动项目滑入到位的 DOM 元素。

所有轮播事件都在轮播本身(即 <div class="carousel">)上触发。

事件类型 描述
slide.bs.carousel 当调用 slide 实例方法时,此事件立即触发。
slid.bs.carousel 当轮播完成幻灯片过渡时,此事件触发。
$('#myCarousel').on('slide.bs.carousel', function () {
  // do something…
})

附加导航 affix.js

示例

附加导航插件会切换 position: fixed; 状态,模拟 position: sticky; 的效果。右侧的子导航栏就是附加导航插件的实际演示。


使用方法

您可以通过数据属性或 JavaScript 手动使用附加导航插件。在这两种情况下,您都必须为附加内容的定位和宽度提供 CSS 样式。

注意:由于 Safari 渲染 bug,请不要在相对定位的元素(如使用了 pull 或 push 的列)中使用附加导航插件。

通过 CSS 定位

附加导航插件会在三个类之间切换,每个类代表一个特定的状态:.affix.affix-top.affix-bottom。您必须为这些类提供样式(除了 .affix 上的 position: fixed; 之外),以处理实际的定位(独立于插件)。

附加导航插件的工作原理如下:

  1. 开始时,插件会添加 .affix-top 类,表示元素处于最顶部位置。此时不需要 CSS 定位。
  2. 滚动经过要附加的元素时,会触发实际的附加操作。此时 .affix 会替换 .affix-top 并设置 position: fixed;(由 Bootstrap 的 CSS 提供)。
  3. 如果定义了底部偏移量,滚动经过它时应该用 .affix-bottom 替换 .affix。由于偏移量是可选的,设置偏移量需要您设置适当的 CSS。在这种情况下,必要时添加 position: absolute;。插件使用数据属性或 JavaScript 选项来确定从那里开始定位元素的位置。

按照上述步骤为下面的任一使用选项设置您的 CSS。

通过数据属性

要轻松地向任何元素添加附加导航行为,只需向要监视的元素添加 data-spy="affix"。使用偏移量来定义何时切换元素的固定状态。

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

通过 JavaScript

通过 JavaScript 调用附加导航插件:

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

选项

选项可以通过数据属性或 JavaScript 传递。对于数据属性,将选项名称附加到 data- 后面,例如 data-offset-top="200"

名称 类型 默认值 描述
offset number | function | object 10 计算滚动位置时从屏幕偏移的像素数。如果提供单个数字,则偏移量将应用于顶部和底部两个方向。要提供唯一的底部和顶部偏移量,只需提供一个对象,例如 offset: { top: 10 }offset: { top: 10, bottom: 5 }。当您需要动态计算偏移量时使用函数。
target selector | node | jQuery element the window object 指定附加导航的目标元素。

方法

.affix(options)

激活您的内容作为附加内容。接受一个可选的选项 object

$('#myAffix').affix({
  offset: 15
})

.affix('checkPosition')

根据相关元素的尺寸、位置和滚动位置重新计算附加导航的状态。.affix.affix-top.affix-bottom 类会根据新状态添加到或从附加内容中移除。每当附加内容或目标元素的尺寸发生变化时,都需要调用此方法,以确保附加内容的正确定位。

$('#myAffix').affix('checkPosition')

事件

Bootstrap 的附加导航插件公开了一些事件,用于挂钩到附加导航功能中。

事件类型 描述
affix.bs.affix 此事件在元素即将被附加之前触发。
affixed.bs.affix 此事件在元素被附加之后触发。
affix-top.bs.affix 此事件在元素即将被附加到顶部之前触发。
affixed-top.bs.affix 此事件在元素被附加到顶部之后触发。
affix-bottom.bs.affix 此事件在元素即将被附加到底部之前触发。
affixed-bottom.bs.affix 此事件在元素被附加到底部之后触发。