JavaScript
使用我们的可选JavaScript插件,让Bootstrap栩栩如生。 了解每个插件,我们的data和编程API选项,等等。
各自独立或整体编译
插件可以单独包含(使用Bootstrap的单独js/dist/*.js
),也可以同时使用bootstrap.js
或缩小的bootstrap.min.js
(不要同时包含两者)。
如果你使用bundler(Webpack、Parcel、Vite…),则可以使用已准备好UMD的/js/dist/*.js
文件。
与JavaScript框架一起使用
虽然Bootstrap CSS可以与任何框架一起使用,但Bootstrap JavaScript与React、Vue和Angular等JavaScript框架并不完全兼容,这些框架假定完全了解DOM。 Bootstrap和框架都可能试图对同一个DOM元素进行变化,从而导致像dropdown这样的错误被卡在open
位置。
对于那些使用这种类型框架的人来说,一个更好的选择是使用特定于框架的包,而不是Bootstrap JavaScript。 以下是一些最受欢迎的选项:
- React: React Bootstrap
Try it yourself! 从twbs/examples repository下载将Bootstrap与React、Next.js和React Bootstrap一起使用的源代码和工作演示。 你也可以在StackBlitz中打开示例.
- Vue: BootstrapVue (Bootstrap 4)
- Vue 3: BootstrapVueNext (Bootstrap 5, currently in alpha)
- Angular: ng-bootstrap
使用Bootstrap作为模块
我们提供一个构建为ESM
(Bootstrap.ESM.js
和Bootstrap.ESM.min.js
)的Bootstrap版本,如果你的目标浏览器支持,它允许你将Bootstrap用作浏览器中的模块。
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
与JS捆绑器相比,在浏览器中使用ESM需要使用完整的路径和文件名,而不是模块名称。 在浏览器中阅读有关JS模块的更多信息。这就是为什么我们使用bootstrap.esm.min.js
而不是上面的bootstrap
。 然而,我们的Popper依赖关系使这一点更加复杂,它将Popper导入到我们的JavaScript中,如下所示:
import * as Popper from "@popperjs/core"
如果按原样尝试,你将在控制台中看到如下错误:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
要解决此问题,可以使用importmap
将任意模块名称解析为完整路径。 如果你的目标浏览器不支持importmap
,需要使用es模块垫片项目。 以下是Bootstrap和Popper的工作原理:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<title>Hello, modularity!</title>
</head>
<body>
<h1>Hello, modularity!</h1>
<button id="popoverButton" type="button" class="btn btn-primary btn-lg" data-bs-toggle="popover" title="ESM in Browser" data-bs-content="Bang!">Custom popover</button>
<script async src="https://cdn.jsdelivr.net/npm/es-module-shims@1/dist/es-module-shims.min.js" crossorigin="anonymous"></script>
<script type="importmap">
{
"imports": {
"@popperjs/core": "https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/esm/popper.min.js",
"bootstrap": "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.esm.min.js"
}
}
</script>
<script type="module">
import * as bootstrap from 'bootstrap'
new bootstrap.Popover(document.getElementById('popoverButton'))
</script>
</body>
</html>
依赖项
一些插件和CSS组件依赖于其他插件。 如果你单独包含插件,请确保在文档中检查这些依赖项。
我们的下拉菜单、弹出菜单和工具提示也依赖于Popper.
Data 属性
几乎所有的Bootstrap插件都可以单独通过HTML和数据属性来启用和配置(我们使用JavaScript功能的首选方式)。 请确保在单个元素上只使用一组data属性(例如,不能从同一按钮触发工具提示和模态。)
As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-
, as in data-bs-animation="{value}"
. Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier"
instead of data-bs-customClass="beautifier"
.
As of Bootstrap 5.2.0, all components support an experimental reserved data attribute data-bs-config
that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}'
and data-bs-title="456"
attributes, the final title
value will be 456
and the separate data attributes will override values given on data-bs-config
. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'
.
The final configuration object is the merged result of data-bs-config
, data-bs-
, and js object
where the latest given key-value overrides the others.
选择器
出于性能原因,我们使用本机querySelector
和querySelectorAll
方法来查询DOM元素,因此必须使用有效选择器。 如果使用诸如collapse:Example
之类的特殊选择器,请确保转义它们。
事件
Bootstrap为大多数插件的独特操作提供自定义事件。 一般来说,它们有不定式和过去分词形式——其中不定式(例如show
)在事件开始时触发,其过去分词形式(例如showed
)在动作完成时触发。
所有不定式事件都提供preventDefault()
功能。 这提供了在操作开始之前停止执行操作的能力。 从事件处理程序返回false也将自动调用preventDefault()
。
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
return event.preventDefault() // stops modal from being shown
})
可编程 API
所有构造函数都接受一个可选的options对象,或者什么都不接受(它用默认行为启动插件):
const myModalEl = document.querySelector('#myModal')
const modal = new bootstrap.Modal(myModalEl) // initialized with defaults
const configObject = { keyboard: false }
const modal1 = new bootstrap.Modal(myModalEl, configObject) // initialized with no keyboard
如果你想获得一个特定的插件实例,每个插件都会公开一个getInstance
方法。 例如,要直接从元素中检索实例,请执行以下操作:
bootstrap.Popover.getInstance(myPopoverEl)
如果没有通过请求的元素启动实例,则此方法将返回null
。
或者,getOrCreateInstance
可以用于获取与DOM元素相关联的实例,或者在未初始化的情况下创建一个新实例。
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
在实例未初始化的情况下,它可以接受并使用可选的配置对象作为第二个参数。
构造函数中的CSS选择器
除了getInstance
和getOrCreateInstance
方法外,所有插件构造函数都可以接受DOM元素或有效的CSS选择器作为第一个参数。 插件元素是通过querySelector
方法找到的,因为我们的插件只支持单个元素。
const modal = new bootstrap.Modal('#myModal')
const dropdown = new bootstrap.Dropdown('[data-bs-toggle="dropdown"]')
const offcanvas = bootstrap.Offcanvas.getInstance('#myOffcanvas')
const alert = bootstrap.Alert.getOrCreateInstance('#myAlert')
异步functions 和 transitions
所有编程API方法都是 异步,并且在 transition 开始后返回给调用方,但在transition 结束前返回。 为了在转换完成后执行操作,你可以侦听相应的事件。
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
此外,对transitioning 组件的方法调用将被忽略。
const myCarouselEl = document.querySelector('#myCarousel')
const carousel = bootstrap.Carousel.getInstance(myCarouselEl) // Retrieve a Carousel instance
myCarouselEl.addEventListener('slid.bs.carousel', 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 !!
dispose
method
虽然在hide()
之后立即使用dispose
方法似乎是正确的,但它会导致不正确的结果。以下是问题使用的示例:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
默认设置
你可以通过修改插件的Constructor.Default
来更改插件的默认设置。默认`object:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
方法和属性
每个Bootstrap插件都公开以下方法和静态属性。
Method | Description |
---|---|
dispose |
Destroys 元素的模态。(删除DOM元素上存储的数据) |
getInstance |
Static方法,该方法允许你获取与DOM元素相关联的模态实例。 |
getOrCreateInstance |
Static方法,它允许你获取与DOM元素相关联的模态实例,或者在它没有初始化的情况下创建一个新实例。 |
Static property | Description |
---|---|
NAME |
返回插件名称。(示例:bootstrap.Tooltip.NAME ) |
VERSION |
每个Bootstrap插件的版本都可以通过插件构造函数的version 属性访问(例如:Bootstrap.Tooltip.version ) |
Sanitizer
工具提示和Popovers使用我们内置的消毒器来消毒接受HTML的选项。
默认的allowList
值如下:
const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
export const 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: [],
dd: [],
div: [],
dl: [],
dt: [],
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: []
}
如果要将新值添加到此默认的allowList
中,可以执行以下操作:
const 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
const 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:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
可选地使用jQuery
你不需要在Bootstrap 5中使用jQuery,但仍然可以将我们的组件与jQuery一起使用。 如果Bootstrap在window
对象中检测到jQuery
,它将在jQuery的插件系统中添加我们的所有组件。 这允许你执行以下操作:
// to enable tooltips with the default configuration
$('[data-bs-toggle="tooltip"]').tooltip()
// to initialize tooltips with given configuration
$('[data-bs-toggle="tooltip"]').tooltip({
boundary: 'clippingParents',
customClass: 'myClass'
})
// to trigger the `show` method
$('#myTooltip').tooltip('show')
我们的其他组件也是如此。
无冲突
有时有必要将Bootstrap插件与其他UI框架一起使用。 在这些情况下,偶尔会发生名称空间冲突。 如果发生这种情况,你可以对要恢复其值的插件调用.noConflict
。
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap不正式支持Prototype或jQueryUI等第三方JavaScript库。 尽管有.noConflict
和按名称命名的事件,但可能存在兼容性问题,你需要自行解决。
jQuery事件
如果window
对象中存在jQuery
,并且<body>
上没有设置data-bs-no-jquery
属性,则引导程序将检测jQuery。 如果找到jQuery,由于jQuery的事件系统,Bootstrap将发出事件。 因此,如果你想监听Bootstrap的事件,你必须使用jQuery方法(.on
,.one
)而不是addEventListener
。
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
被禁用的JavaScript
当JavaScript被禁用时,Bootstrap的插件没有特殊的fallback。 如果你关心这种情况下的用户体验,请使用<noscript>
向用户解释情况(以及如何重新启用JavaScript),和/或添加你自己的自定义fallback。