简体   繁体   English

javascript - 检测 ctrl 键被按下或向上,keypress 事件不会触发

[英]javascript - detect ctrl key pressed or up, keypress event doesn't trigger

I see some similar questions here (like JavaScript: Check if CTRL button was pressed ) but my problem is actually the event triggering.我在这里看到了一些类似的问题(比如JavaScript: Check if CTRL button was pressed ),但我的问题实际上是事件触发。 My js code:我的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;
        }
    }

The event triggers for any other keys except the ctrl .该事件触发除ctrl之外的任何其他键。
I need to also trigger it for ctrl .我还需要为ctrl触发它。
I can't use jQuery/prototype/whatever so those solutions are not acceptable.我不能使用 jQuery/prototype/whatever,所以这些解决方案是不可接受的。

So... how can I detect the ctrl ?那么......我怎样才能检测到ctrl

Try using if (e.ctrlKey) .尝试使用if (e.ctrlKey)

MDN: event.ctrlKey MDN:事件.ctrlKey

Using onkeydown rather than onkeypress may help.使用 onkeydown 而不是 onkeypress 可能会有所帮助。

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

Note: The onkeypress event is not fired for all keys (eg ALT, CTRL, SHIFT, ESC) in all browsers.注意:onkeypress 事件并非针对所有浏览器中的所有键(例如 ALT、CTRL、SHIFT、ESC)触发。 To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.要仅检测用户是否按下了某个键,请改用 onkeydown 事件,因为它适用于所有键。

Your event has a property named ctrlKey.您的事件有一个名为 ctrlKey 的属性。 You can check this to look if the key was pressed or not.您可以检查此项以查看该键是否被按下。 See snippet below for more control like keys.请参阅下面的片段以获取更多控制,例如键。

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

This is basically Rick Hoving's answer, but it uses keydown like Danielle Cerisier suggests这基本上是 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 请注意,在按 ctrl 之前,您可能需要在预览框内单击才能聚焦

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

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