JavaScript - 检测Ctrl键是否按下或释放,keypress事件未触发。

57

我看到这里有一些类似的问题(比如JavaScript:检查是否按下了CTRL键),但我的问题实际上是事件触发。我的JS代码:

    // Listen to keyboard. 
    window.onkeypress = listenToTheKey;
    window.onkeyup = listenToKeyUp;

    /*
        Gets the key pressed and send a request to the associated function
        @input key
    */
    function listenToTheKey(e)
    {
        if (editFlag == 0)
        {
            // If delete key is pressed calls delete
            if (e.keyCode == 46)
                deleteNode();

            // If insert key is pressed calls add blank
            if (e.keyCode == 45)
                createBlank();

            if (e.keyCode == 17)
                ctrlFlag = 1;
        }
    }

事件触发除了ctrl键之外的任何其他键。
我需要同时触发它也是ctrl
我不能使用jQuery/prototype/任何其他解决方案,因此这些解决方案不可接受。

那么...我如何检测ctrl


2
这个代码有问题吗:if (e.ctrlKey) { .... } 无法正常工作吗? - Sudhir Bastakoti
4个回答

74

24

使用 onkeydown 而不是 onkeypress 可能会更有帮助。

来自 http://www.w3schools.com/jsref/event_onkeypress.asp

注意: 在某些浏览器中,onkeypress 事件不能为某些键触发(例如ALT、CTRL、SHIFT、ESC)。如果只想检测用户是否按下了某个键,请改用 onkeydown 事件,因为它适用于所有键。


有一个有趣的事实是,Enter键的键码==13,但Ctrl+Enter键的键码==10。 - Yan King Yin

18

您的事件具有名为 ctrlKey 的属性。您可以检查此属性以查看是否按下了该键。请参见以下代码段,以获取更多控制类似的按键。

function detectspecialkeys(e){
    var evtobj=window.event? event : e
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
        alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectspecialkeys

1
这基本上就是Rick Hoving的答案,但它使用了Danielle Cerisier建议的keydown

function detectspecialkeys(e) {
  var evtobj = window.event ? event : e
  if (evtobj.ctrlKey)
    console.log("You pressed ctrl")
}
document.onkeydown = detectspecialkeys

Please note that you may have to click inside the preview box to focus before pressing ctrl


1
请注意window.event已经过时。参见链接 - Jono Job
@JonoJob,应该使用什么替代? - undefined
1
哦,我猜这只是意味着在我不想与旧的东西兼容的代码中,我可以使用e代替evtobj - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接