js intercept keyboard events and keyboard events

A keyboard event

  • onkeydown: When you press the keyboard trigger

  • onkeypress: Press the key is activated when the value of

    注意: onkeypressPress the Ctrl, Alt, Shift, Metakeys so no value, this event does not have a key trigger for value, when pressed to trigger keydown event, then this event fires

  • onkeyup: This event is triggered when you release the keyboard

II. Key Combinations

  • ctrl-related
  • alt-related
  • meta (Mac keyboard is a four flowers, Windows keyboard is the Windows key) related

  • shift-related

Others are writing a similar example

Such as ctrl + c

window.onkeydown=function (e) {
    if (e.ctrlKey) {     //其他几个类似shiftkey,altkey,metakey
        if( e.key == 'c'){     //这里最好用keycode可以无视大小写,你要是区分大小写最好这样写
            console.log('ctrl+c')
        }
    }
}

//一般简写
window.onkeydown=function (e) {
    if (e.ctrlKey&&e.key == 'c'){console.log('ctrl+c')}
}

III. Interceptors preventDefault

For example interceptionctrl+h事件

<script>
    window.onkeydown=function (e) {
        if (e.ctrlKey) {
                if( e.key == 'h'){
                    console.log('ctrl+h')
                    e.preventDefault();
                }
        }
    }
</script>

But some specific keys can not intercept why not go into too useless to before, such as Chrome

CtrlN
CtrlShiftN
CtrlT
CtrlShiftT
CtrlW
CtrlShiftW
//没法拦截

Guess you like

Origin www.cnblogs.com/pythonywy/p/11906747.html