如果未聚焦于表单,则捕获删除键

发布于 2024-12-15 10:00:04 字数 263 浏览 6 评论 0原文

我有一个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筱武穆 2024-12-22 10:00:04

我想到的第一件事是在 inputtextarea 字段上 stopPropagation,然后是 preventDefault不应在文档上触发。

JQuery 伪代码:

$('input, textarea').keypress(e, function(e){e.stopPropagation();});
$(document).keypress(e, function(e){if(delete) e.preventDefault();});

另一种可能性是检查文档关键事件的原始目标。

事件回调:

var originalElement = e.srcElement || e.originalTarget;
if(orignalElement.tagName === 'INPUT' or orignalElement.tagName === 'TEXTAREA'){ return; }
// else do your delete key stuff

如果您使用 jQuery,第一行应该已过时,因为它为您标准化了事件,并且您可以使用 e.target 来获取 originalTarget

The first thing that came into my mind, is to stopPropagation on the input and textarea fields, then the preventDefault should not be triggered on the document.

JQuery pseudo code:

$('input, textarea').keypress(e, function(e){e.stopPropagation();});
$(document).keypress(e, function(e){if(delete) e.preventDefault();});

Another possiblity is the check the orignal target on the key event of the document.

Event callback:

var originalElement = e.srcElement || e.originalTarget;
if(orignalElement.tagName === 'INPUT' or orignalElement.tagName === 'TEXTAREA'){ return; }
// else do your delete key stuff

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 the originalTarget

冧九 2024-12-22 10:00:04

我更喜欢的方法是这样的:

$(window).keyup(function(e) {
  if(e.keyCode == 46 && $("input:focus, textarea:focus").length == 0) {
    e.preventDefault();
    alert("delete key pressed!");
  }
});

但是,我不确定您是否能够覆盖后退按钮行为 - 考虑到滥用的可能性,Chrome 似乎不太可能允许它。

My prefered approach would be something like this:

$(window).keyup(function(e) {
  if(e.keyCode == 46 && $("input:focus, textarea:focus").length == 0) {
    e.preventDefault();
    alert("delete key pressed!");
  }
});

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文