JS 组件
想知道哪些组件明确需要我们的 JavaScript 以及 Floating UI 或 Vanilla Calendar Pro 吗?
- 用于关闭的 Alert
- 用于切换状态和复选框/单选按钮功能的按钮
- 用于所有幻灯片行为、控件和指示器的 Carousel
- 用于切换内容可见性的 Collapse
- 用于日期选择的 Datepicker(还需要 Vanilla Calendar Pro)
- 对话框,用于显示、定位和滚动行为
- 用于显示和定位的菜单(还需要 Floating UI)
- 导航栏,用于扩展我们的 Collapse 和 Drawer 插件以实现响应式行为
- Nav,用于导航标记和样式;Tab 插件,用于切换标签窗格
- 抽屉,用于显示、定位和滚动行为
- Scrollspy,用于滚动行为和导航更新
- 用于显示和关闭的 Toast
- 用于显示和定位的 Tooltip 和 popover(还需要 Floating UI)
单独或编译
插件可以单独包含(使用 Bootstrap 的单独 js/dist/*.js),或使用 bootstrap.js 或压缩后的 bootstrap.min.js 一次性全部包含(不要同时包含两者)。
如果你使用打包器(Webpack、Parcel、Vite……),你可以只导入需要的插件,打包器会自动对其余部分进行 tree-shake:
import { Toast, Tooltip } from 'bootstrap'
TypeScript
Bootstrap 的插件使用 TypeScript 编写,并附带内置的类型声明——无需 @types/bootstrap 包。主入口点和 js/dist/*.js 下的每个单独插件都完全类型化,包括每个插件的配置选项:
import { Tooltip } from 'bootstrap'
const tooltip = Tooltip.getOrCreateInstance('#example')
tooltip.show()
如果你需要为自己的包装器添加类型,每个插件模块还会导出其配置对象类型(例如 TooltipConfig)。
与 JavaScript 框架一起使用
虽然 Bootstrap CSS 可以与任何框架一起使用,但 Bootstrap JavaScript 与 React、Vue 和 Angular 等假定完全了解 DOM 的 JavaScript 框架并不完全兼容。Bootstrap 和框架都可能尝试修改同一个 DOM 元素,从而导致诸如菜单卡在“打开”位置之类的错误。
对于使用此类框架的人来说,更好的替代方案是使用框架特定的包而不是 Bootstrap JavaScript。以下是一些最流行的选项:
- React:React Bootstrap(Bootstrap 5)
- Vue 2:BootstrapVue(Bootstrap 4)
- Vue 3:BootstrapVueNext(Bootstrap 5)
- Angular:ng-bootstrap(Bootstrap 5)或 ngx-bootstrap(Bootstrap 5)
将 Bootstrap 用作模块
自己试一试! 从 twbs/examples 仓库下载将 Bootstrap 用作 ES 模块的源代码和可运行演示。你也可以在 StackBlitz 中打开该示例。
Bootstrap 的 JavaScript 构建为原生 ES 模块。捆绑包包含 Floating UI 和 Vanilla Calendar Pro。你可以直接在浏览器中加载它:
<script type="module">
import { Toast } from './bootstrap.bundle.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
非捆绑文件(bootstrap.js 和 bootstrap.min.js)引用了 @floating-ui/dom 和 vanilla-calendar-pro。浏览器必须在 Bootstrap 运行之前解析这两个裸模块说明符。当你直接加载非捆绑文件时,请使用导入映射:
<!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@6.0.0-alpha.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MKn5NWVBEuQXJE7TSKSgPUmMiSCmVTfCsR+VSSeQpHnoyJQZZFn/kBn+Ht5jZDPQ" crossorigin="anonymous">
<title>Hello, modularity!</title>
</head>
<body>
<h1>Hello, modularity!</h1>
<button id="popoverButton" type="button" class="btn-solid theme-primary btn-lg" data-bs-toggle="popover" title="ESM in Browser" data-bs-content="Bang!">Custom popover</button>
<script type="importmap">
{
"imports": {
"@floating-ui/dom": "https://cdn.jsdelivr.net/npm/@floating-ui/dom@1.8.0/dist/floating-ui.dom.esm.min.js",
"vanilla-calendar-pro": "https://cdn.jsdelivr.net/npm/vanilla-calendar-pro@3.4.0/index.mjs",
"bootstrap": "https://cdn.jsdelivr.net/npm/bootstrap@6.0.0-alpha.2/dist/js/bootstrap.min.js"
}
}
</script>
<script type="module">
import * as bootstrap from 'bootstrap'
new bootstrap.Popover(document.getElementById('popoverButton'))
</script>
</body>
</html>
不依赖 Floating UI 的组件(如 Toast、Alert、Collapse 等)可以单独导入,无需任何导入映射:
<script type="module">
import Toast from './js/dist/toast.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
依赖项
一些插件和 CSS 组件依赖其他插件。如果你单独包含插件,请务必在文档中检查这些依赖项。
我们的菜单、popover 和 tooltip 也依赖 Floating UI。我们的日期选择器还依赖 Vanilla Calendar Pro。
data 属性
几乎所有 Bootstrap 插件都可以仅通过 HTML 使用 data 属性来启用和配置(我们使用 JavaScript 功能的首选方式)。请务必在单个元素上只使用一组 data 属性(例如,你不能从同一个按钮触发 tooltip 和 dialog。)
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".
All components support a 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)在事件开始时触发,而其过去分词形式(例如 shown)在操作完成时触发。
所有不定式事件都提供 preventDefault() 功能。这提供了在操作开始前停止其执行的能力。从事件处理程序返回 false 也会自动调用 preventDefault()。
const myDialogEl = document.querySelector('#myDialog')
myDialogEl.addEventListener('show.bs.dialog', event => {
return event.preventDefault() // stops dialog from being shown
})
编程式 API
所有构造函数都接受一个可选的选项对象或不接受任何参数(这将以默认行为初始化插件):
const myDialogEl = document.querySelector('#myDialog')
const dialog = new bootstrap.Dialog(myDialogEl) // initialized with defaults
const configObject = { keyboard: false }
const dialog1 = new bootstrap.Dialog(myDialogEl, configObject) // initialized with no keyboard
如果你想获取特定的插件实例,每个插件都暴露一个 getInstance 方法。例如,直接从元素检索实例:
bootstrap.Popover.getInstance(myPopoverEl)
如果未在请求的元素上初始化实例,此方法将返回 null。
或者,可以使用 getOrCreateInstance 获取与 DOM 元素关联的实例,或者在未初始化的情况下创建一个新实例。
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
如果实例未初始化,它可能会接受并使用一个可选的配置对象作为第二个参数。
组件实例
不同的组件类型可以共享一个元素。通过各自的组件类检索每个实例。例如,Combobox 在其 toggle 上同时注册了一个 Combobox 和一个 Menu:
const toggle = document.querySelector('[data-bs-toggle="combobox"]')
const combobox = bootstrap.Combobox.getOrCreateInstance(toggle)
const menu = bootstrap.Menu.getInstance(toggle)
每种组件类型在每个元素上有一个实例。构造该类型的另一个实例会销毁前一个。使用 getOrCreateInstance() 复用现有实例。
调用 dispose() 会移除该组件的注册和监听器。除非组件拥有并销毁它们,否则其他组件类型仍保持注册。例如,combobox.dispose() 也会销毁其 Menu。请让 Combobox 管理该 Menu,而不是单独替换或销毁它。
共享注册并不能使组件行为的所有组合都兼容。每个组件的标记、事件和生命周期要求仍然适用。
构造函数中的 CSS 选择器
除了 getInstance 和 getOrCreateInstance 方法之外,所有插件构造函数都可以接受一个 DOM 元素或有效的 CSS 选择器作为第一个参数。插件元素使用 querySelector 方法查找,因为我们的插件只支持单个元素。
const dialog = new bootstrap.Dialog('#myDialog')
const menu = new bootstrap.Menu('[data-bs-toggle="menu"]')
const drawer = bootstrap.Drawer.getInstance('#myDrawer')
const alert = bootstrap.Alert.getOrCreateInstance('#myAlert')
Promise 与过渡
所有编程式 API 方法都是异步的,在过渡开始后、但结束之前就返回给调用者。
显示或隐藏组件的方法返回一个 promise。promise 在过渡结束时 resolve,因此你可以 await 该方法而不是监听事件。
const collapse = bootstrap.Collapse.getOrCreateInstance('#myCollapse')
await collapse.show()
// The collapsible area is now expanded
这些方法返回 promise:
| 方法 | 组件 |
|---|---|
show、hide、toggle | Collapse、Combobox、Datepicker、Dialog、Drawer、Menu、Popover、Tooltip |
show、hide | Toast |
show | Tab |
close | Alert |
promise resolve 时没有值。它在对应的 shown.bs.*、hidden.bs.* 或 closed.bs.* 事件触发的同一时刻 resolve,因此两种方式都会在同一时间运行你的代码。当你必须对每次变化(包括并非由你自己的代码发起的变化)做出反应时,请使用事件。
const myDrawerEl = document.querySelector('#myDrawer')
const drawer = bootstrap.Drawer.getOrCreateInstance(myDrawerEl)
// Await the method you called…
await drawer.hide()
saveState()
// …or listen for every hide, whoever started it
myDrawerEl.addEventListener('hidden.bs.drawer', () => {
saveState()
})
因为每个方法都返回 promise,你可以按顺序运行步骤而无需嵌套监听器。
const dialog = bootstrap.Dialog.getOrCreateInstance('#myDialog')
const toast = bootstrap.Toast.getOrCreateInstance('#myToast')
await dialog.hide()
await toast.show()
当调用不执行任何操作时,promise 也会 resolve——例如组件已经打开、某个监听器在 show.bs.* 事件上调用了 preventDefault(),或者你在过渡中途销毁了组件。因此 await 永远不会挂起,但它也不会告诉你状态是否发生了变化。当这很重要时,请自行检查状态。
此外,对正在过渡的组件调用方法将被忽略。对于上述返回 promise 的方法,此类调用会立即 resolve。它不会等待正在进行的过渡结束。
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 方法
不要在 hide() 之后立即调用 dispose。此时隐藏过渡仍在进行,因此组件会在过渡中途被拆除。请先 await promise:
const toast = bootstrap.Toast.getInstance('#myToast')
await toast.hide()
toast.dispose()
基于事件的等效方式同样有效:
const myToastEl = document.querySelector('#myToast')
const toast = bootstrap.Toast.getInstance(myToastEl)
myToastEl.addEventListener('hidden.bs.toast', () => {
toast.dispose()
})
toast.hide()
默认设置
你可以通过修改插件的 Constructor.Default 对象来更改插件的默认设置:
// changes default for the toast plugin's `autohide` option to false
bootstrap.Toast.Default.autohide = false
方法和属性
每个 Bootstrap 插件都暴露以下方法和静态属性。
| 方法 | 描述 |
|---|---|
dispose | 销毁元素的插件实例。(移除 DOM 元素上存储的数据) |
getInstance | 静态方法,允许你获取与 DOM 元素关联的插件实例。 |
getOrCreateInstance | 静态方法,允许你获取与 DOM 元素关联的插件实例,或在未初始化的情况下创建一个新实例。 |
| 静态属性 | 描述 |
|---|---|
NAME | 返回插件名称。(示例:bootstrap.Tooltip.NAME) |
VERSION | 每个 Bootstrap 插件的版本可以通过插件构造函数的 VERSION 属性访问(示例:bootstrap.Tooltip.VERSION) |
清理器
一些 JavaScript 组件可以在其配置中渲染或接受任意 HTML。为防止跨站脚本(XSS)攻击,这些组件在将任何接受 HTML 的选项渲染到页面之前,使用我们内置的内容清理器对其进行清理。内容清理默认启用。特别是:
- 如果配置为这样做,popover 和 tooltip 可以将任意 HTML 渲染到页面。
- Nav 溢出可以为其图标选项(
moreIcon和[data-bs-overflow-icon])接受 HTML。
默认情况下允许用于 tooltip 和 popover 内容的标签和属性如下。任何未明确允许的标签或属性将在清理期间被移除:
const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
export const DefaultAllowlist: SanitizerAllowList = {
// 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: []
}
图标选项使用单独的、更严格的允许列表,涵盖默认 SVG 图标和常见的行内图标标记:
/**
* Allowlist for icon HTML options (NavOverflow `moreIcon`,
* and markup supplied via `[data-bs-overflow-icon]`). Covers the default SVG
* icons plus common inline-icon markup. Event-handler attributes and tags not
* listed here are stripped by `sanitizeHtml`.
*/
export const DefaultIconAllowlist: SanitizerAllowList = {
'*': ['class', 'role', ARIA_ATTRIBUTE_PATTERN],
// Attribute names are matched lowercased (see allowedAttribute). `viewBox` is
// listed as `viewbox` so the default SVG icons keep their coordinate system.
svg: ['xmlns', 'width', 'height', 'viewbox', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'focusable'],
path: ['d', 'fill', 'stroke', 'stroke-width', 'fill-rule', 'clip-rule'],
line: ['x1', 'y1', 'x2', 'y2', 'stroke', 'stroke-width', 'stroke-linecap'],
circle: ['cx', 'cy', 'r', 'fill', 'stroke', 'stroke-width'],
rect: ['x', 'y', 'width', 'height', 'rx', 'ry', 'fill', 'stroke', 'stroke-width'],
polyline: ['points', 'fill', 'stroke', 'stroke-width'],
polygon: ['points', 'fill', 'stroke', 'stroke-width'],
g: ['fill', 'stroke', 'stroke-width', 'transform'],
// No `use` here: `href` / `xlink:href` on <use> can load external SVG
// fragments. Apps that need sprites can extend this allowlist deliberately.
span: [],
i: []
}
使用这些高级选项时请务必谨慎。 有关更多信息,请参阅 OWASP 的跨站脚本防护速查表。仅因禁用或修改内容清理而导致的漏洞不在 Bootstrap 安全模型的范围之内。
你可以向这个默认 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)
你也可以用专用库替换我们的清理器,例如 DOMPurify:
const myTooltipEl = document.querySelector('#myTooltip')
const tooltip = new bootstrap.Tooltip(myTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
禁用 JavaScript
Bootstrap 的插件在禁用 JavaScript 时没有特殊的降级方案。如果你关心这种情况下的用户体验,请使用 <noscript> 向用户说明情况(以及如何重新启用 JavaScript),和/或添加你自己的自定义降级方案。