JavaScript
Bring Bootstrap to life with our optional JavaScript plugins. 使用我们可选的JavaScript插件,让Bootstrap变得生动起来。Learn about each plugin, our data and programmatic API options, and more.了解每个插件、我们的数据和编程API选项等。
Individual or compiled个体的或已编译的
Plugins can be included individually (using Bootstrap’s individual 插件可以单独包含(使用Bootstrap的单个js/dist/*.js
), or all at once using bootstrap.js
or the minified bootstrap.min.js
(don’t include both).js/dist/*.js
),也可以同时使用bootstrap.js
或小型bootstrap.min.js
(不要同时包含两者)。
If you use a bundler (Webpack, Rollup…), you can use 如果您使用捆绑程序(Webpack、Rollup…),您可以使用UMD就绪的/js/dist/*.js
files which are UMD ready./js/dist/*.js
文件。
Using Bootstrap as a module作为一个模块使用Bootstrap
We provide a version of Bootstrap built as 我们提供了一个构建为ESM
(bootstrap.esm.js
and bootstrap.esm.min.js
) which allows you to use Bootstrap as a module in your browser, if your targeted browsers support it.ESM
的Bootstrap版本(bootstrap.esm.js
和bootstrap.esm.min.js
),如果目标浏览器支持,它允许您将Bootstrap用作浏览器中的一个模块。
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Incompatible plugins不兼容插件
Due to browser limitations, some of our plugins, namely Dropdown, Tooltip and Popover plugins, cannot be used in a 由于浏览器的限制,我们的一些插件,即下拉菜单、工具提示和Popover插件,不能用于<script>
tag with module
type because they depend on Popper. <script>
标记模块类型,因为它们依赖于Popper。For more information about the issue see here.有关此问题的更多信息,请参阅此处。
Dependencies依赖关系
Some plugins and CSS components depend on other plugins. 一些插件和CSS组件依赖于其他插件。If you include plugins individually, make sure to check for these dependencies in the docs.如果您单独包含插件,请确保在文档中检查这些依赖项。
Our dropdowns, popovers and tooltips also depend on Popper.我们的下拉菜单、弹出框和工具提示也依赖于Popper。
Still want to use jQuery? It’s possible!还想使用jQuery吗?这是可能的!
Bootstrap 5 is designed to be used without jQuery, but it’s still possible to use our components with jQuery. Bootstrap5设计用于不使用jQuery的情况,但仍然可以将我们的组件与jQuery一起使用。If Bootstrap detects 如果Bootstrap在jQuery
in the window
object it’ll add all of our components in jQuery’s plugin system; this means you’ll be able to do $('[data-bs-toggle="tooltip"]').tooltip()
to enable tooltips. window
对象中检测到jQuery
,它将在jQuery的插件系统中添加所有组件;这意味着您将能够执行$('[data-bs-toggle="tooltip"]').tooltip()
来启用工具提示。tooltip()
以启用工具提示。The same goes for our other components.我们的其他组件也是如此。
Data attributes数据属性
Nearly all Bootstrap plugins can be enabled and configured through HTML alone with data attributes (our preferred way of using JavaScript functionality). 几乎所有的Bootstrap插件都可以通过HTML和数据属性(我们使用JavaScript功能的首选方式)单独启用和配置。Be sure to only use one set of data attributes on a single element (e.g., you cannot trigger a tooltip and modal from the same button.)确保在单个元素上仅使用一组数据属性(例如,不能从同一按钮触发工具提示和模态框。)
Selectors选择器
Currently to query DOM elements we use the native methods 目前为了查询DOM元素,出于性能原因,我们使用原生方法querySelector
and querySelectorAll
for performance reasons, so you have to use valid selectors.querySelector
和querySelectorAll
,因此必须使用有效的选择器。
If you use special selectors, for example: 如果使用特殊的选择器,例如:collapse:Example
be sure to escape them.collapse:Example
,请确保将其转义。
Events事件
Bootstrap provides custom events for most plugins' unique actions. Bootstrap为大多数插件的独特操作提供自定义事件。Generally, these come in an infinitive and past participle form - where the infinitive (ex. 一般来说,它们以不定式和过去分词的形式出现——不定式(如show
) is triggered at the start of an event, and its past participle form (ex. shown
) is triggered on the completion of an action.show
)在事件开始时触发,其过去分词形式(如shown
)在动作完成时触发。
All infinitive events provide 所有不定式事件都提供preventDefault()
functionality. preventDefault()
功能。This provides the ability to stop the execution of an action before it starts. 这提供了在操作开始之前停止执行操作的能力。Returning false from an event handler will also automatically call 从事件处理程序返回preventDefault()
.false
也将自动调用preventDefault()
。
var myModal = document.getElementById('myModal')
myModal.addEventListener('show.bs.modal', function (event) {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
jQuery events事件
Bootstrap will detect jQuery if jQuery
is present in the window
object and there is no data-bs-no-jquery
attribute set on <body>
. window
对象中存在jQuery
,并且<body>
上没有设置data-bs-no-jquery
属性,则Bootstrap程序将检测jQuery。If jQuery is found, Bootstrap will emit events thanks to jQuery’s event system. 如果找到jQuery,则由于jQuery的事件系统,Bootstrap程序将发出事件。So if you want to listen to Bootstrap’s events, you’ll have to use the jQuery methods (因此,如果要侦听Bootstrap程序的事件,必须使用jQuery方法(.on
, .one
) instead of addEventListener
..on
、.one
)而不是addEventListener
。
$('#myTab a').on('shown.bs.tab', function () {
// do something...
})
Programmatic API编程API
All constructors accept an optional options object or nothing (which initiates a plugin with its default behavior):所有构造函数都接受一个可选的选项对象或不接受任何对象(这将以其默认行为启动插件):
var myModalEl = document.getElementById('myModal')
var modal = new bootstrap.Modal(myModalEl) // initialized with defaults
var modal = new bootstrap.Modal(myModalEl, { keyboard: false }) // initialized with no keyboard
If you’d like to get a particular plugin instance, each plugin exposes a 如果您想获得一个特定的插件实例,每个插件都会公开一个getInstance
method. getInstance
方法。In order to retrieve it directly from an element, do this: 为了直接从元素中检索它,请执行以下操作:bootstrap.Popover.getInstance(myPopoverEl)
.bootstrap.Popover.getInstance(myPopoverEl)
。
CSS selectors in constructors构造函数中的CSS选择器
You can also use a CSS selector as the first argument instead of a DOM element to initialize the plugin. 您还可以使用CSS选择器作为第一个参数,而不是DOM元素来初始化插件。Currently the element for the plugin is found by the 目前,该插件的元素由querySelector
method since our plugins support a single element only.querySelector
方法找到,因为我们的插件只支持单个元素。
var modal = new bootstrap.Modal('#myModal')
var dropdown = new bootstrap.Dropdown('[data-bs-toggle="dropdown"]')
Asynchronous functions and transitions异步函数和转换
All programmatic API methods are asynchronous and return to the caller once the transition is started but before it ends.所有编程API方法都是异步的,并且在转换开始但结束之前返回给调用方。
In order to execute an action once the transition is complete, you can listen to the corresponding event.为了在转换完成后执行操作,您可以侦听相应的事件。
var myCollapseEl = document.getElementById('myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', function (event) {
// Action to execute once the collapsible area is expanded
})
In addition a method call on a transitioning component will be ignored.此外,对转换组件的方法调用将被忽略。
var myCarouselEl = document.getElementById('myCarousel')
var carousel = bootstrap.Carousel.getInstance(myCarouselEl) // Retrieve a Carousel instance
myCarouselEl.addEventListener('slid.bs.carousel', function (event) {
carousel.to('2') // Will slide to the slide 2 as soon as the transition to slide 1 is finished
})
carousel.to('1') // Will start sliding to the slide 1 and returns to the caller
carousel.to('2') // !! Will be ignored, as the transition to the slide 1 is not finished !!
Default settings默认设置
You can change the default settings for a plugin by modifying the plugin’s 您可以通过修改插件的Constructor.Default
object:Constructor.Default
对象来更改插件的默认设置:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
No conflict (only if you use jQuery)去掉冲突(仅当使用jQuery时)
Sometimes it is necessary to use Bootstrap plugins with other UI frameworks. 有时有必要将Bootstrap插件与其他UI框架一起使用。In these circumstances, namespace collisions can occasionally occur. 在这些情况下,有时会发生名称空间冲突。If this happens, you may call 如果发生这种情况,您可以在希望还原其值的插件上调用.noConflict
on the plugin you wish to revert the value of..noConflict
。
var bootstrapButton = $.fn.button.noConflict()
// return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton
// give $().bootstrapBtn the Bootstrap functionality
Version numbers版本号
The version of each of Bootstrap’s plugins can be accessed via the 可以通过插件构造函数的VERSION
property of the plugin’s constructor. VERSION
属性访问每个Bootstrap插件的版本。For example, for the tooltip plugin:例如,对于工具提示插件:
bootstrap.Tooltip.VERSION // => "5.1.0"
No special fallbacks when JavaScript is disabled禁用JavaScript时没有特殊的回退
Bootstrap’s plugins don’t fall back particularly gracefully when JavaScript is disabled. 当禁用JavaScript时,Bootstrap的插件不会特别优雅地后退。If you care about the user experience in this case, use 如果您关心这种情况下的用户体验,请使用<noscript>
to explain the situation (and how to re-enable JavaScript) to your users, and/or add your own custom fallbacks.<noscript>
向用户解释情况(以及如何重新启用JavaScript),和/或添加您自己的自定义回退。
Third-party libraries第三方图书馆
Bootstrap does not officially support third-party JavaScript libraries like Prototype or jQuery UI. Bootstrap不正式支持Prototype或jQueryUI等第三方JavaScript库。Despite 尽管有.noConflict
and namespaced events, there may be compatibility problems that you need to fix on your own..noConflict
和命名空间事件,但可能存在需要您自己修复的兼容性问题。
Sanitizer
Tooltips and Popovers use our built-in sanitizer to sanitize options which accept HTML.工具提示和弹出窗口使用我们的内置净化剂净化接受HTML的选项。
The default 默认allowList
value is the following:allowList
值如下所示:
var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
var DefaultAllowlist = {
// Global attributes allowed on any supplied element below.
'*': ['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', 'srcset', 'alt', 'title', 'width', 'height'],
li: [],
ol: [],
p: [],
pre: [],
s: [],
small: [],
span: [],
sub: [],
sup: [],
strong: [],
u: [],
ul: []
}
If you want to add new values to this default 如果要将新值添加到此默认allowList
you can do the following:allowList
,可以执行以下操作:
var myDefaultAllowList = bootstrap.Tooltip.Default.allowList
// To allow table elements
myDefaultAllowList.table = []
// To allow td elements and data-bs-option attributes on td elements
myDefaultAllowList.td = ['data-bs-option']
// You can push your custom regex to validate your attributes.
// Be careful about your regular expressions being too lax
var myCustomRegex = /^data-my-app-[\w-]+/
myDefaultAllowList['*'].push(myCustomRegex)
If you want to bypass our sanitizer because you prefer to use a dedicated library, for example DOMPurify, you should do the following:如果您想绕过我们的消毒剂,因为您更喜欢使用专用库,例如DOMPurify,您应该执行以下操作:
var yourTooltipEl = document.getElementById('yourTooltip')
var tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn: function (content) {
return DOMPurify.sanitize(content)
}
})