在javascript中捕获ctrl + z组合键 [英] Capturing ctrl+z key combination in javascript

查看:1962
本文介绍了在javascript中捕获ctrl + z组合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码在javascript中捕获 ctrl + z 组合键:

I am trying to capture ctrl+z key combination in javascript with this code:

<html>
<head>
    <title>Untitled Document</title>
</head>
<body>

    <script type='text/javascript'>
        function KeyPress(e) {
            var evtobj = window.event? event : e


            //test1 if (evtobj.ctrlKey) alert("Ctrl");
            //test2 if (evtobj.keyCode == 122) alert("z");
            //test 1 & 2
            if (evtobj.keyCode == 122 && evtobj.ctrlKey) alert("Ctrl+z");
        }

        document.onkeypress = KeyPress;
    </script>

</body>
</html>

如果我按住 ctrl ,评论行test1会生成警报键,然后按任意其他键。

Commented line "test1" generates the alert if I hold down the ctrl key and press any other key.

如果按 z 键,则注释行test2会生成警报。

Commented line "test2" generates the alert if I press the z key.

按照测试1& 2之后的行将它们放在一起,然后按住 ctrl 键,然后按 z 键没有按预期生成警报。

Put them together as per the line after "test 1 & 2", and holding down the ctrl key then pressing the z key does not generate the alert as expected.

代码有什么问题?

推荐答案


  1. 使用 onkeydown (或 onkeyup ),而不是 onkeypress

  2. 使用 keyCode 90,而不是122

  1. Use onkeydown (or onkeyup), not onkeypress
  2. Use keyCode 90, not 122

在线演示: http://jsfiddle.net/29sVC/

为了澄清,密钥代码与字符代码不同。

字符代码用于文本(它们根据编码而不同,但在很多cas中es 0-127仍为ASCII码)。键码映射到键盘上的键。例如,在unicode字符中,0x22909表示好。没有很多键盘(如果有的话)实际上有一把钥匙。

Character codes are for text (they differ depending on the encoding, but in a lot of cases 0-127 remain ASCII codes). Key codes map to keys on a keyboard. For example, in unicode character 0x22909 means 好. There aren't many keyboards (if any) who actually have a key for this.

操作系统负责使用用户配置的输入方法将击键转换为字符代码。结果将发送到按键事件。 (而keydown和keyup响应用户按下按钮,而不是键入文本。)

The OS takes care of transforming keystrokes to character codes using the input methods that the user configured. The results are sent to the keypress event. (Whereas keydown and keyup respond to the user pressing buttons, not typing text.)

这篇关于在javascript中捕获ctrl + z组合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆