简体   繁体   English

释放CTRL-F时如何检测CTRL键的“ key up”事件?

[英]How to detect the “key up” event of the CTRL key when releasing CTRL-F?

I am trying to detect the "key up" event of the CTRL key when releasing CTRL+F in the browser. 在浏览器中释放CTRL + F时,我试图检测CTRL键的“向上键”事件。 I have tried this: 我已经试过了:

    $(document).keyup(function(e){
        if (e.ctrlKey){ // note that I'm not even checking for the F key here
            console.log("CTRL up");
        }
    });

but it doesn't work, the event is not triggered. 但它不起作用,不会触发该事件。 How can I do this? 我怎样才能做到这一点?

If you're using jQuery, you can always do: 如果您使用的是jQuery,则始终可以执行以下操作:

$(document).keydown(function(e) {
  if(e.ctrlKey && (e.keyCode === 70 || e.keyCode === 102)) // f or F
    alert("Ctrl+F was pressed!!");
});

from your code: 从您的代码:

  • never use keyup , by that time the browser already fired its own event and the event will never be bubble down to the document again, at least you should use keydown 永远不要使用keyup ,到那时浏览器已经触发了自己的事件,并且该事件再也不会冒泡到文档中了,至少您应该使用keydown
  • you will never be able to override the browser behavior, in this case, bring the search input box 您将永远无法覆盖浏览器的行为,在这种情况下,请带上搜索输入框

e.ctrlKey returns false on keyUp event and true on keyDown. e.ctrlKey在keyUp事件上返回false,在keyDown事件上返回true。 You can test (e.keyCode === 17) condition. 您可以测试(e.keyCode === 17)条件。

You were very close. 你很亲近 I always find it easiest to output the e variable in order to see exactly what's going on and filter down from there. 我总是发现最简单的方法是输出e变量,以便准确了解正在发生的事情并从那里进行过滤。 See my jsfiddle for a working example. 有关工作示例,请参见我的jsfiddle。

$(document).keyup(function (e) {
  if(e.originalEvent.key == 'Control') {
    console.log("CTRL keyup event.");
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM