Flowbite Drawer(Off-canvas)组件完全指南:数据属性、四向定位与 Drawer API 实战
Flowbite Drawer(Off-canvas)组件完全指南:数据属性、四向定位与 Drawer API 实战
Flowbite 的 Drawer 组件(又称 off-canvas)是一类固定在文档页面某侧、可展开与收起的面板元素,常用于侧边导航、联系表单、信息展示及其他用户操作场景。本指南将基于 content/components/drawer.md 与 src/components/drawer/index.ts 的源码实现,系统讲解 Drawer 的初始化方式、全部数据属性、四种方向定位、body 滚动与 backdrop 控制、滑动边缘(swipeable edge)功能,以及通过 Drawer API 进行程序化控制的完整方法,读完即可在项目中直接复刻官方示例并扩展出自定义抽屉面板。
使用前提:引入 Flowbite JavaScript
Drawer 的交互依赖 data-* 属性解析与 Drawer API,因此需要先引入 Flowbite 的 JavaScript 文件。按照 getting-started/quickstart 的说明,可通过本地文件或 CDN 引入:
<!-- 本地构建产物 -->
<script src="../path/to/flowbite/dist/flowbite.min.js"></script>
<!-- 或使用 CDN -->
<script src="https://cdn.jsdelivr.net/npm/flowbite@<版本号>/dist/flowbite.min.js"></script>
从源码角度看,引入的 flowbite.min.js 会注册 window.Drawer 与 window.initDrawers(见 src/config/global.ts),并在 initFlowbite() 时统一调用所有组件的初始化函数(见 src/components/index.ts)。页面加载后,凡带有 data-drawer-* 属性的元素都会被自动解析并创建 Drawer 实例。
默认 Drawer:初始化与显示控制
核心数据属性
要初始化一个 Drawer,首先需要在触发元素(例如一个按钮)上设置 data-drawer-target="{id}",其值必须等于 Drawer 组件自身的 id。随后可以用以下属性控制 Drawer 的显示、隐藏与切换,值同样为 Drawer 的 id:
| 属性 | 作用 |
|---|---|
data-drawer-show="{id}" |
显示 Drawer 组件 |
data-drawer-hide="{id}" |
隐藏 Drawer 组件 |
data-drawer-toggle="{id}" |
切换 Drawer 组件的可见性 |
可访问性(Accessibility)
为兼顾无障碍访问,官方建议:
- 在触发 Drawer 的元素上添加
aria-controls="{id}"; - 在 Drawer 组件上添加
aria-labelledby="{id}",其值为 Drawer 标题元素的 id。
源码在初始化与显隐过程中还会自动维护状态属性:init() 时为 Drawer 设置 aria-hidden="true"(src/components/drawer/index.ts 第 58 行);show() 时移除 aria-hidden 并添加 aria-modal="true" 与 role="dialog";hide() 时则恢复 aria-hidden="true" 并移除这两个属性。也就是说,除了手动声明,Drawer 的模态语义也会随显隐自动同步。
防止闪烁:默认隐藏 Drawer
为避免页面初次渲染时 Drawer 闪现,应给 Drawer 元素应用以下类使其处于画布之外(off-canvas):
transition-transform left-0 top-0 -translate-x-full
其中 -translate-x-full 将左侧 Drawer 沿 X 轴平移出视口,transition-transform 保证展开/收起时有平滑过渡。
默认 Drawer 完整示例
<!-- drawer init and toggle -->
<div class="text-center">
<button class="inline-flex items-center justify-center text-white bg-brand box-border border border-transparent hover:bg-brand-strong focus:ring-4 focus:ring-brand-medium shadow-xs font-medium leading-5 rounded-base text-sm px-4 py-2.5 focus:outline-none" type="button" data-drawer-target="drawer-example" data-drawer-show="drawer-example" aria-controls="drawer-example">
Show drawer
</button>
</div>
<!-- drawer component -->
<div id="drawer-example" class="fixed top-0 left-0 z-40 h-screen p-4 overflow-y-auto transition-transform -translate-x-full bg-neutral-primary-soft w-96 border-e border-default" tabindex="-1" aria-labelledby="drawer-label">
<div class="border-b border-default pb-4 mb-5 flex items-center">
<h5 id="drawer-label" class="inline-flex items-center text-lg font-medium text-body">
Drawer heading
</h5>
<button type="button" data-drawer-hide="drawer-example" aria-controls="drawer-example" class="text-body bg-transparent hover:text-heading hover:bg-neutral-tertiary rounded-base w-9 h-9 absolute top-2.5 end-2.5 flex items-center justify-center">
<span class="sr-only">Close menu</span>
</button>
</div>
<p class="mb-3 text-sm text-body">Upgrade your Figma toolkit with a design system built on top Flowbite CSS featuring variants, style guide and auto layout.</p>
<p class="mb-5 text-sm text-body">Recommended for professional developers and companies building enterprise-level.</p>
<div class="flex items-center gap-4">
<button type="button" class="text-body bg-neutral-secondary-medium box-border border border-default-medium hover:bg-neutral-tertiary-medium hover:text-heading focus:ring-4 focus:ring-neutral-tertiary shadow-xs font-medium leading-5 rounded-base text-sm px-4 py-2.5 focus:outline-none">Pricing & FAQ</button>
<button type="button" class="inline-flex items-center justify-center text-white bg-brand box-border border border-transparent hover:bg-brand-strong focus:ring-4 focus:ring-brand-medium shadow-xs font-medium leading-5 rounded-base text-sm px-4 py-2.5 focus:outline-none">
Get access
</button>
</div>
</div>
要点:Drawer 本体使用 fixed 定位脱离文档流,z-40 保证层级高于页面内容,overflow-y-auto 允许内部内容滚动,w-96(或 w-80)控制面板宽度。窗口右上角的关闭按钮通过 data-drawer-hide="drawer-example" 触发隐藏。
Drawer 导航栏:把侧边导航放进抽屉
Drawer 最常见的用途之一就是承载导航菜单。官方示例在 data-drawer-navigation 中放入品牌 Logo、可折叠的子菜单(借助 data-collapse-toggle 与 Collapse 组件)以及带徽标/计数器的导航项,结构如下:
<!-- drawer component -->
<div id="drawer-navigation" class="fixed top-0 left-0 z-40 h-screen p-4 overflow-y-auto transition-transform -translate-x-full bg-neutral-primary-soft w-80 border-e border-default" tabindex="-1" aria-labelledby="drawer-navigation-label">
<!-- 头部:Logo + 关闭按钮 -->
<div class="border-b border-default pb-4 flex items-center">
<a href="https://flowbite.com/" class="flex items-center space-x-2 rtl:space-x-reverse">
<img src="https://flowbite.com/docs/images/logo.svg" class="h-6 w-6" alt="Flowbite Logo" />
<span class="self-center text-lg font-semibold whitespace-nowrap text-heading">Flowbite</span>
</a>
<button type="button" data-drawer-hide="drawer-navigation" aria-controls="drawer-navigation" class="...">...</button>
</div>
<!-- 导航列表 -->
<div class="py-5 overflow-y-auto">
<ul class="space-y-2 font-medium">
<li>
<a href="#" class="flex items-center px-2 py-1.5 text-body rounded-base hover:bg-neutral-tertiary hover:text-fg-brand group">
<span class="ms-3">Dashboard</span>
</a>
</li>
<!-- 可折叠子菜单:E-commerce -->
<li>
<button type="button" class="..." aria-controls="dropdown-example" data-collapse-toggle="dropdown-example">
<span class="flex-1 ms-3 text-left rtl:text-right whitespace-nowrap">E-commerce</span>
</button>
<ul id="dropdown-example" class="hidden py-2 space-y-2">
<li><a href="#" class="pl-10 ...">Products</a></li>
<li><a href="#" class="pl-10 ...">Billing</a></li>
<li><a href="#" class="pl-10 ...">Invoice</a></li>
</ul>
</li>
<!-- Kanban(带 Pro 徽标) -->
<li>
<a href="#" class="...">
<span class="flex-1 ms-3 whitespace-nowrap">Kanban</span>
<span class="bg-neutral-secondary-medium border border-default-medium text-heading text-xs font-medium px-1.5 py-0.5 rounded-sm">Pro</span>
</a>
</li>
<!-- Inbox(带未读计数徽标) -->
<li>
<a href="#" class="...">
<span class="flex-1 ms-3 whitespace-nowrap">Inbox</span>
<span class="inline-flex items-center justify-center w-4.5 h-4.5 ms-2 text-xs font-medium text-fg-danger-strong bg-danger-soft border border-danger-subtle rounded-full">2</span>
</a>
</li>
</ul>
</div>
</div>
这个模式说明 Drawer 内部可以自由嵌套任意 HTML,并与 Flowbite 的 Collapse(折叠菜单)、Badge(Pro 徽标)等组件组合,形成完整的管理后台侧边栏。
在 Drawer 中放表单:联系表单与表单元素
联系表单(Contact form)
Drawer 同样适合承载联系表单。示例 drawer-contact 中,表单包含邮箱、主题、消息三个字段和提交按钮,底部附公司邮箱与电话:
<div id="drawer-contact" class="fixed top-0 left-0 z-40 h-screen p-4 overflow-y-auto transition-transform -translate-x-full bg-neutral-primary-soft w-80 border-e border-default" tabindex="-1" aria-labelledby="drawer-contact-label">
<!-- 头部:标题 + 关闭按钮 -->
<div class="border-b border-default pb-4 mb-5 flex items-center">
<h5 id="drawer-label-contact" class="inline-flex items-center text-lg font-medium text-body">
Contact Us
</h5>
<button type="button" data-drawer-hide="drawer-contact" aria-controls="drawer-contact" class="...">...</button>
</div>
<form class="mb-6 space-y-4">
<label for="input-group-1" class="block mb-2.5 text-sm font-medium text-heading">Your Email<span class="ms-1 text-fg-danger">*</span></label>
<div class="relative">
<input type="text" id="input-group-1" class="block w-full ps-9 pe-3 py-2.5 bg-neutral-secondary-medium border border-default-medium text-heading text-sm rounded-base focus:ring-brand focus:border-brand px-3 py-2.5 shadow-xs placeholder:text-body" placeholder="name@flowbite.com" required>
</div>
<label for="input-group-2" class="block mb-2.5 text-sm font-medium text-heading">Subject<span class="ms-1 text-fg-danger">*</span></label>
<div class="relative">
<input type="text" id="input-group-2" class="..." placeholder="Let us know how we can help you" required>
</div>
<label for="message" class="block mb-2.5 text-sm font-medium text-heading">Your message</label>
<textarea id="message" rows="4" class="..." placeholder="Write your thoughts here..."></textarea>
<button type="submit" class="w-full text-white bg-brand ...">Send message</button>
</form>
<p class="mb-2 text-sm text-body"><a href="#" class="hover:underline">info@company.com</a></p>
<p class="text-sm text-body"><a href="#" class="hover:underline">212-456-7890</a></p>
</div>
表单元素(Form elements)
Drawer 内还可以放入更复杂的表单,包括 Flowbite 的 Datepicker 日期选择器。示例 drawer-form 是一个“新建事件”表单,包含标题、描述、日期选择、邀请嘉宾邮箱及提交按钮:
<div id="drawer-form" class="fixed top-0 left-0 z-40 h-screen p-4 overflow-y-auto transition-transform -translate-x-full bg-neutral-primary-soft w-80 border-e border-default" tabindex="-1" aria-labelledby="drawer-form-label">
<div class="border-b border-default pb-4 mb-5 flex items-center">
<h5 id="drawer-label-event" class="text-lg font-medium text-body">New event</h5>
<button type="button" data-drawer-hide="drawer-form" aria-controls="drawer-form" class="...">...</button>
</div>
<form class="mb-6 space-y-4">
<div>
<label for="title" class="block mb-2.5 text-sm font-medium text-heading">Title<span class="ms-1 text-fg-danger">*</span></label>
<input type="text" id="title" class="..." placeholder="Apple Keynote" required />
</div>
<label for="description" class="block mb-2.5 text-sm font-medium text-heading">Description</label>
<textarea id="description" rows="4" class="..." placeholder="Write your description here..."></textarea>
<div class="relative max-w-sm">
<input datepicker id="default-datepicker" type="text" class="..." placeholder="Select date">
</div>
<div class="mb-4">
<label for="guests" class="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-white">Invite guests</label>
<div class="relative">
<input type="search" id="guests" class="..." placeholder="Add guest email" required />
<button class="absolute flex items-center end-1.5 top-1/2 -translate-y-1/2 ...">
<span class="text-xs font-semibold">Add</span>
</button>
</div>
</div>
<button type="submit" class="inline-flex items-center justify-center w-full text-white bg-brand ...">
Create event
</button>
</form>
</div>
四向定位:Placement 选项
通过 data-drawer-placement="{top|right|bottom|left}" 数据属性可以把 Drawer 定位到页面的上、右、下、左侧,默认值为 left。
从源码看,定位由 _getPlacementClasses() 方法决定(src/components/drawer/index.ts 第 228-267 行),每种定位都包含三组类:base(基础定位类,初始化时固定添加)、active(显示时添加、隐藏时移除)、inactive(隐藏时添加、显示时移除):
| placement | base | active | inactive |
|---|---|---|---|
top |
top-0 left-0 right-0 |
transform-none |
-translate-y-full |
right |
right-0 top-0 |
transform-none |
translate-x-full |
bottom |
bottom-0 left-0 right-0 |
transform-none |
translate-y-full |
left |
left-0 top-0 |
transform-none |
-translate-x-full |
也就是说,Drawer 的展开/收起本质上是动态切换 transform-none 与对应的 translate-* 平移类,配合 transition-transform 产生滑动动画。
左侧 Drawer(Left drawer)
<button type="button" data-drawer-target="drawer-left-example" data-drawer-show="drawer-left-example" data-drawer-placement="left" aria-controls="drawer-left-example">Show left drawer</button>
<div id="drawer-left-example" class="fixed top-0 left-0 z-40 h-screen bg-neutral-primary-soft p-4 overflow-y-auto transition-transform -translate-x-full w-96" tabindex="-1" aria-labelledby="drawer-left-label">
<!-- 内容 -->
</div>
要使 Drawer 占满页面整个高度,需要添加 h-screen 类。
右侧 Drawer(Right drawer)
<button type="button" data-drawer-target="drawer-right-example" data-drawer-show="drawer-right-example" data-drawer-placement="right" aria-controls="drawer-right-example">Show right drawer</button>
<div id="drawer-right-example" class="fixed top-0 right-0 z-40 h-screen p-4 overflow-y-auto transition-transform translate-x-full bg-neutral-primary-soft w-96" tabindex="-1" aria-labelledby="drawer-right-label">
<!-- 内容 -->
</div>
注意右侧 Drawer 的隐藏态类改为 translate-x-full(向右移出视口),基础定位类为 top-0 right-0。
顶部 Drawer(Top drawer)
<button type="button" data-drawer-target="drawer-top-example" data-drawer-show="drawer-top-example" data-drawer-placement="top" aria-controls="drawer-top-example">Show top drawer</button>
<div id="drawer-top-example" class="fixed top-0 left-0 right-0 z-40 w-full p-4 transition-transform -translate-y-full bg-neutral-primary-soft border-b border-default" tabindex="-1" aria-labelledby="drawer-top-label">
<!-- 内容 -->
</div>
顶部 Drawer 用 left-0 right-0 w-full 横向铺满,隐藏态类为 -translate-y-full(向上移出视口)。
底部 Drawer(Bottom drawer)
<button type="button" data-drawer-target="drawer-bottom-example" data-drawer-show="drawer-bottom-example" data-drawer-placement="bottom" aria-controls="drawer-bottom-example">Show bottom drawer</button>
<div id="drawer-bottom-example" class="fixed bottom-0 left-0 right-0 z-40 w-full p-4 overflow-y-auto transition-transform bg-neutral-primary-soft border-t border-default transform-none" tabindex="-1" aria-labelledby="drawer-bottom-label">
<!-- 内容 -->
</div>
底部 Drawer 使用 bottom-0 left-0 right-0 w-full,隐藏态类为 translate-y-full。源码中 show()/hide() 会依据 _options.placement 自动在这些类之间切换,因此标记中的显式类只需保证初始隐藏即可。
控制 Body 滚动
默认情况下,Drawer 显示时会禁用页面主体的滚动(body scrolling disabled),可通过 data-drawer-body-scrolling="{true|false}" 属性开启或关闭:
data-drawer-body-scrolling="false":Drawer 显示时页面主体不可滚动(默认行为)。data-drawer-body-scrolling="true":Drawer 显示时页面主体仍可滚动。
<!-- 禁用 body 滚动(默认) -->
<button type="button" data-drawer-target="drawer-disable-body-scrolling" data-drawer-show="drawer-disable-body-scrolling" data-drawer-body-scrolling="false" aria-controls="drawer-disable-body-scrolling">Show body scrolling disabled</button>
<!-- 启用 body 滚动 -->
<button type="button" data-drawer-target="drawer-body-scrolling" data-drawer-show="drawer-body-scrolling" data-drawer-body-scrolling="true" aria-controls="drawer-body-scrolling">Show body scrolling</button>
源码中的实现位于 show() 与 hide() 方法:当 bodyScrolling 为 false 时,show() 给 document.body 添加 overflow-hidden,hide() 时移除(src/components/drawer/index.ts 第 135-138、181-184 行)。注意:抽屉面板自身的滚动不受影响,面板内的内容仍可借助 overflow-y-auto 独立滚动。
Backdrop 遮罩层
Backdrop 用于在 Drawer 显示时压暗背景元素,并且点击遮罩外部会自动隐藏 Drawer。可通过 data-drawer-backdrop="{true|false}" 开启或关闭:
data-drawer-backdrop="true":启用遮罩层(默认)。data-drawer-backdrop="false":禁用遮罩层。
<!-- 启用遮罩(默认) -->
<button type="button" data-drawer-target="drawer-backdrop" data-drawer-show="drawer-backdrop" data-drawer-backdrop="true" aria-controls="drawer-backdrop">Show drawer with backdrop</button>
<!-- 禁用遮罩 -->
<button type="button" data-drawer-target="drawer-disabled-backdrop" data-drawer-show="drawer-disabled-backdrop" data-drawer-backdrop="false" aria-controls="drawer-disabled-backdrop">Show drawer without backdrop</button>
从源码看,show() 时若 backdrop 为 true,会调用 _createBackdrop() 动态创建 div 元素,默认类为 bg-dark-backdrop/70 fixed inset-0 z-30,并监听其 click 事件自动执行 hide()(src/components/drawer/index.ts 第 186-217 行);hide() 时则调用 _destroyBackdropEl() 将其移除。由于遮罩是运行时动态创建而非预置在 HTML 中,若关闭遮罩(data-drawer-backdrop="false"),点击外部区域将不会关闭 Drawer。
Swipeable edge:滑动边缘露出
Edge 功能允许 Drawer 在完全隐藏时仍露出一小部分,提示用户这里存在一个可展开的面板。通过以下属性组合实现:
data-drawer-edge="{true|false}":开启/关闭边缘功能。data-drawer-edge-offset="bottom-[*px]":设置 Drawer 隐藏时露出的偏移高度(接收 Tailwind CSS 类),默认值为bottom-[60px]。- 配合
data-drawer-toggle="id",点击露出的“边缘”部分即可切换 Drawer 的显示状态。
<button type="button" data-drawer-target="drawer-swipe" data-drawer-show="drawer-swipe" data-drawer-placement="bottom" data-drawer-edge="true" data-drawer-edge-offset="bottom-[60px]" aria-controls="drawer-swipe">Show swipeable drawer</button>
<div id="drawer-swipe" class="fixed z-40 w-full overflow-y-auto bg-neutral-primary-soft border-t border-default rounded-t-base transition-transform bottom-0 left-0 right-0 translate-y-full bottom-[60px]" tabindex="-1" aria-labelledby="drawer-swipe-label">
<!-- 可点击的边缘头部,用于展开 -->
<div class="p-4 cursor-pointer hover:bg-neutral-secondary-soft" data-drawer-toggle="drawer-swipe">
<span class="absolute w-8 h-1 -translate-x-1/2 bg-neutral-quaternary rounded-lg top-3 left-1/2"></span>
<h5 id="drawer-swipe-label" class="inline-flex items-center text-base text-body font-medium">Add widget</h5>
</div>
<!-- 网格化的组件选择区 -->
<div class="grid grid-cols-3 gap-4 p-4 lg:grid-cols-4">...</div>
</div>
源码在 _getPlacementClasses() 中专门处理了 bottom-edge 分支:其 inactive 类为 translate-y-full 加上 this._options.edgeOffset(默认 bottom-[60px]),因此隐藏时抽屉不是完全移出视口,而是底部保留 60px 的露头区域(src/components/drawer/index.ts 第 254-259 行)。show()/hide() 时若 edge 为 true,则切换到 placement + '-edge' 对应的类组。
Drawer API:JavaScript 程序化控制
除了数据属性,Drawer 还提供了完整的 JavaScript API,可以创建实例、调用方法操控组件,并自定义 placement、backdrop、body scrolling 等行为选项。
对象参数(Object parameters)
| 参数 | 类型 | 是否必需 | 说明 |
|---|---|---|---|
targetEl |
Element | 必需 | 将主 Drawer 元素作为 JavaScript 对象传入 |
options |
Object | 可选 | 设置 Drawer 的默认状态、位置及其他选项 |
instanceOptions |
Object | 可选 | 允许为添加到 Instance Manager 的实例设置自定义 ID,并可指定是否覆盖已有实例 |
选项(Options)
| 选项 | 类型 | 说明 |
|---|---|---|
placement |
String | 设置 Drawer 相对文档主体的位置,取值 {top|right|bottom|left},默认 left |
backdrop |
Boolean | 启用或禁用遮罩层,取值 true / false |
bodyScrolling |
Boolean | 启用或禁用 Drawer 激活时的 body 滚动,取值 true / false |
edge |
Boolean | 启用或禁用边缘功能(隐藏时露出一部分),取值 true / false |
edgeOffset |
String | 设置 Drawer 隐藏时的露出高度,默认 bottom-[60px] |
backdropClasses |
String | 用一串 Tailwind CSS 工具类覆盖默认遮罩样式 |
onShow() |
Function | Drawer 显示后的回调函数 |
onHide() |
Function | Drawer 隐藏后的回调函数 |
onToggle() |
Function | Drawer 可见性切换后的回调函数 |
这些选项与源码中的 Default 常量一一对应(src/components/drawer/index.ts 第 7-17 行),构造函数通过 { ...Default, ...options } 合并用户配置;类型定义见 src/components/drawer/types.ts。
方法(Methods)
| 方法 | 说明 |
|---|---|
show() |
显示 Drawer 元素 |
hide() |
隐藏 Drawer 元素 |
toggle() |
切换 Drawer 元素的可见性 |
isVisible() |
检查元素当前是否可见 |
updateOnShow(callback) |
设置 Drawer 显示后的回调函数 |
updateOnHide(callback) |
设置 Drawer 隐藏后的回调函数 |
updateOnToggle(callback) |
设置 Drawer 可见性切换后的回调函数 |
此外,从 src/components/drawer/interface.ts 可以看到实例还暴露了 isHidden()、destroy()、removeInstance()、destroyAndRemoveInstance() 以及事件监听器管理方法(addEventListenerInstance、removeAllEventListenerInstances、getAllEventListenerInstances),方便在动态页面中彻底清理组件实例。
JavaScript 实例示例
首先准备目标元素与选项对象:
// 设置 Drawer 菜单元素
const $targetEl = document.getElementById('drawer-js-example');
// 带默认值的选项
const options = {
placement: 'right',
backdrop: true,
bodyScrolling: false,
edge: false,
edgeOffset: '',
backdropClasses: 'bg-dark/50 fixed inset-0 z-30',
onHide: () => {
console.log('drawer is hidden');
},
onShow: () => {
console.log('drawer is shown');
},
onToggle: () => {
console.log('drawer has been toggled');
},
};
// 实例选项对象
const instanceOptions = {
id: 'drawer-js-example',
override: true
};
初始化 Drawer 实例:
import { Drawer } from 'flowbite';
/*
* $targetEl (required)
* options (optional)
* instanceOptions (optional)
*/
const drawer = new Drawer($targetEl, options, instanceOptions);
使用 show 和 hide 方法直接控制显示与隐藏:
// 显示 drawer
drawer.show();
// 隐藏 drawer
drawer.hide();
使用 toggle 切换可见性、isVisible 检查状态:
// 切换 drawer
drawer.toggle();
// 返回 true 或 false
drawer.isVisible();
对应的 HTML 结构(供上述 JS 使用):
<!-- drawer component -->
<div id="drawer-js-example" class="fixed top-0 left-0 z-40 h-screen p-4 overflow-y-auto transition-transform -translate-x-full bg-neutral-primary-soft border-e border-default w-80" tabindex="-1" aria-labelledby="drawer-js-example">
<!-- 头部与导航内容,可参考 Drawer navigation 示例 -->
<div class="py-5 overflow-y-auto">
<ul class="space-y-2 font-medium">
<li><a href="#" class="flex items-center px-2 py-1.5 ...">Dashboard</a></li>
<!-- 更多导航项 -->
</ul>
</div>
</div>
TypeScript 用法
如果使用 Flowbite 的 TypeScript 配置,可以导入 Drawer 的类、参数与选项类型:
import { Drawer } from 'flowbite';
import type { DrawerOptions, DrawerInterface } from 'flowbite';
import type { InstanceOptions } from 'flowbite';
// 设置 Drawer 菜单元素
const $targetEl: HTMLElement = document.getElementById('drawer-js-example');
// 带默认值的选项
const options: DrawerOptions = {
placement: 'right',
backdrop: true,
bodyScrolling: false,
edge: false,
edgeOffset: '',
backdropClasses: 'bg-gray-900/50 dark:bg-gray-900/80 fixed inset-0 z-30',
onHide: () => {
console.log('drawer is hidden');
},
onShow: () => {
console.log('drawer is shown');
},
onToggle: () => {
console.log('drawer has been toggled');
},
};
// 实例选项对象
const instanceOptions: InstanceOptions = {
id: 'drawer-js-example',
override: true
};
/*
* $targetEl (required)
* options (optional)
* instanceOptions (optional)
*/
const drawer: DrawerInterface = new Drawer($targetEl, options, instanceOptions);
// 显示 drawer
drawer.show();
数据属性与 Drawer API 的底层联动
理解底层机制有助于排查问题。initDrawers()(src/components/drawer/index.ts 第 316-454 行)在初始化时做了四件事:
- 扫描所有
[data-drawer-target]元素,读取data-drawer-placement、data-drawer-body-scrolling、data-drawer-backdrop、data-drawer-edge、data-drawer-edge-offset属性并创建Drawer实例;若目标 id 不存在,会在控制台输出错误提示。 - 为所有
[data-drawer-toggle]元素绑定click事件,调用实例的toggle()。 - 为所有
[data-drawer-dismiss]、[data-drawer-hide]元素绑定click事件,调用hide()。 - 为所有
[data-drawer-show]元素绑定click事件,调用show()。
所有实例都会注册到 Flowbite 的 Instance Manager(instances.addInstance('Drawer', ...)),这也是 instanceOptions.id 与 override 参数的用途所在——可参考 getting-started/javascript 中对 Instance Manager 与实例选项的说明。
除此之外,Drawer 在 init() 时会向 document 注册 keydown 监听器:当用户按下 Escape 键且 Drawer 可见时自动隐藏(src/components/drawer/index.ts 第 66-77 行),这是 Drawer 默认可通过 Esc 关闭行为的实现来源;destroy() 时该监听器会被移除。
小结
Flowbite Drawer 组件兼具“零 JS 配置”的数据属性方案与完整的 JavaScript/TypeScript API:通过 data-drawer-target/show/hide/toggle 四组属性即可完成初始化与显隐控制,通过 data-drawer-placement 实现四向定位,通过 data-drawer-body-scrolling、data-drawer-backdrop、data-drawer-edge/data-drawer-edge-offset 精细调控滚动、遮罩与边缘露出行为;当需要更复杂的程序化控制时,new Drawer(targetEl, options, instanceOptions) 配合 show()/hide()/toggle()/isVisible() 等方法与回调函数,足以支撑侧边导航、联系表单、事件创建面板等各类实战场景。更完整的组件变体可参考原文档 content/components/drawer.md 以及源码 src/components/drawer/index.ts 中的实现。
