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

前端 未结 3 936
再見小時候
再見小時候 2020-12-05 13:03

I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:

    // Lis         


        
相关标签:
3条回答
  • 2020-12-05 13:25

    Your event has a property named 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
    
    0 讨论(0)
  • 2020-12-05 13:44

    Using onkeydown rather than onkeypress may help.

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

    Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

    0 讨论(0)
  • 2020-12-05 13:46

    Try using if (e.ctrlKey).

    MDN: event.ctrlKey

    0 讨论(0)
提交回复
热议问题