Skip to content

Instantly share code, notes, and snippets.

@coodoo
Created March 8, 2021 07:11
Show Gist options
  • Save coodoo/51e2050aa4e047481b7c04c8f556b27c to your computer and use it in GitHub Desktop.
Save coodoo/51e2050aa4e047481b7c04c8f556b27c to your computer and use it in GitHub Desktop.

Revisions

  1. coodoo created this gist Mar 8, 2021.
    6 changes: 6 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    useHotkey(['Meta', 'c'], () => {
    console.log( `要跑 1`, )
    })
    useHotkey(['ctrl', 'c'], () => {
    console.log( `要跑 2`, )
    })
    23 changes: 23 additions & 0 deletions useHotkey.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    const useHotkey = (def, fn) => {
    const target = def.map(d => d.toLowerCase()).join('-')
    // console.log( `目標字串`, target )
    //
    useEffect(() => {
    //
    const handler = evt => {
    const keys = []
    if(evt.metaKey) keys.push('meta')
    if(evt.ctrlKey) keys.push('ctrl')
    if(evt.altKey) keys.push('alt')
    keys.push(evt.key.toLowerCase())
    // console.log( `最終 keys`, keys )
    if(keys.join('-') === target){
    console.log( `中了`, keys )
    }
    }

    document.addEventListener('keydown', handler)
    console.log( `掛了`, )
    return window.removeEventListener('keydown', handler)
    }, [])
    }