在Vue中按斜杠时获得焦点输入
我见过许多网站,其中可以通过按斜杠 (Shift + 7) 来聚焦搜索栏或类似内容。一个例子是 MDN Web 文档。我想为我的 Vue 应用程序实现这个。 Vue 文档提到了最常用键的键修饰符,例如 .enter
或 .tab
,但没有 Slash 的修饰符。此外,由于用户应该能够在页面上的任何位置触发事件,因此事件侦听器不能应用于输入元素本身。但是,我不知道如何将其应用到整个网站,因为 Vue 应用程序通常会注入到主体内的 div
或类似元素中。
I've seen many websites where the search bar or similar can be focused by pressing Slash (Shift + 7). One example would be the MDN Web Docs. I want to implement this for my Vue application. The Vue documentation mentions key modifiers for the most commonly used keys, like .enter
or .tab
, but there is no modifier for Slash. Also, since the user should be able to trigger the event anywhere on the page, the event listener cannot be applied to the input element itself. However, I don't know how to apply it to the whole website, since Vue applications are typically injected into a div
or similar element inside the body.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于像这样的边缘情况,可以使用常规的 javascript 事件侦听器。
您可以使用 Vue 生命周期方法来添加和删除侦听器。
这是一个工作示例:
另一个解决方案可能是像 v-hotkey 这样的库,它添加了自定义指令。
For edge cased like these, it's okay to use regular javascript event listeners.
You can use Vue lifecycle methods to add and remove listeners.
Here's a working example:
Another solution could be a library like v-hotkey that adds a custom directive.