如果未聚焦于表单,则捕获删除键
我有一个使用 SVG 绘制点的 Web 应用程序,我想添加通过按 delete 键删除选定点的功能。我可以捕获整个文档的 delete 键按下(或向上)并阻止默认事件(Chrome 的默认行为是返回页面),但这显然会阻止所有删除事件,因此 delete 按钮在表单中不再起作用。
有没有办法对其进行设置,以便 delete 键在表单/输入中按预期工作,但在应用程序中的其他任何地方都可以用作自定义删除功能?
I have a web app which plots points with SVG, I want to add the ability to delete a selected point by pressing the delete key. I can capture delete keydown (or up) for the entire document and prevent the default event (Chrome's default behavior is to go back a page), however this obviously blocks all delete events so the delete button no longer works in forms.
Is there a way to set it up so that the delete key works as intended in forms/inputs but when anywhere else in the app it can be used as a custom delete function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想到的第一件事是在
input
和textarea
字段上stopPropagation
,然后是preventDefault
不应在文档
上触发。JQuery 伪代码:
另一种可能性是检查文档关键事件的原始目标。
事件回调:
如果您使用 jQuery,第一行应该已过时,因为它为您标准化了事件,并且您可以使用
e.target
来获取originalTarget
The first thing that came into my mind, is to
stopPropagation
on theinput
andtextarea
fields, then thepreventDefault
should not be triggered on thedocument
.JQuery pseudo code:
Another possiblity is the check the orignal target on the key event of the document.
Event callback:
The first line should be obsolete, if you are using jQuery, because it normalized the event for you, and you can use
e.target
to get theoriginalTarget
我更喜欢的方法是这样的:
但是,我不确定您是否能够覆盖后退按钮行为 - 考虑到滥用的可能性,Chrome 似乎不太可能允许它。
My prefered approach would be something like this:
However, I'm not sure if you'll be able to override the back button behaviour - it seems unlikely that Chrome would allow it, given the potential for abuse.