如何通过Mousetrap实现Bootstrap Offcanvas的键盘切换(开/关)功能?
问题:实现按F键切换收藏侧边栏的显示/关闭
我编写了如下代码,通过按下键盘上的“f”键来显示收藏侧边栏:
Mousetrap.bind('f', function () { const bsOffcanvas = new bootstrap.Offcanvas('#favorites'); bsOffcanvas.show(); });
但存在一个问题:再次按下“f”键时,侧边栏不会关闭,而是尝试再次打开,导致背景持续变暗。请问是否可以实现“切换”功能,让再次按下“f”键时关闭侧边栏?
解决方案
问题根源是每次按F键都会新建bootstrap.Offcanvas实例,重复调用show()会叠加遮罩层,造成背景变暗。以下几种方法可实现切换功能:
方法一:复用实例+状态判断
提前初始化一次侧边栏实例,后续按F键时根据当前状态执行显示/关闭操作:
// 全局保存实例,避免重复创建 const favoritesOffcanvas = new bootstrap.Offcanvas('#favorites'); Mousetrap.bind('f', function () { const isShown = favoritesOffcanvas._isShown; isShown ? favoritesOffcanvas.hide() : favoritesOffcanvas.show(); });
方法二:直接使用Bootstrap的toggle方法
Bootstrap Offcanvas组件内置了toggle方法,可一键切换显示状态,代码最简洁:
const favoritesOffcanvas = new bootstrap.Offcanvas('#favorites'); Mousetrap.bind('f', function () { favoritesOffcanvas.toggle(); });
方法三:通过DOM类判断状态(无需提前保存实例)
如果不想全局保存实例,可通过检查DOM元素的show类判断当前状态:
Mousetrap.bind('f', function () { const offcanvasEl = document.getElementById('favorites'); const isShown = offcanvasEl.classList.contains('show'); if (isShown) { bootstrap.Offcanvas.getInstance(offcanvasEl).hide(); } else { new bootstrap.Offcanvas(offcanvasEl).show(); } });
推荐使用方法二,直接利用组件原生能力,代码简洁且不易出错。
内容的提问来源于stack exchange,提问作者Hardist
相关产品推荐
相关产品推荐

