js监听键盘按下弹起

264 阅读1分钟
import storejs from 'storejs'
/**
 * 使用方法
 * const keyboard = new FnKeyDown({}) 根据当前业务排除获取焦点后按钮继续监听
 * keyboard.monitorCallback = (type, event) => {}  type === 1 ? '按下' : '抬起'
 * const keyboard = new FnKeyDown({isMonitorKeyCode: false}) 单纯的监听按键
 */
export class FnKeyDown {
  curKeyCode: string;
  monitorKeyCode: number;
  isMonitorKeyCode: boolean;
  isFocus: boolean;
  keydownEven: any;
  keyupEven: any;
  focusEven: any;
  blurEven: any;
  constructor ({ isMonitorKeyCode = true }: any) { //
    this.curKeyCode = ''
    // 是否开启监听
    this.isMonitorKeyCode = isMonitorKeyCode
    // 是否获取焦点,排除按钮监听
    this.isFocus = false
    // 默认监听空格键
    this.monitorKeyCode = 32
    // 按下回调
    this.keydownEven = null
    // 抬起回调
    this.keyupEven = null
    // 获取焦点回调
    this.focusEven = null
    // 失去焦点回调
    this.blurEven = null
    this.init()
  }

  init () {
    this.removeEvent()
    this.monitorKeyCode = this.getKeyCode().keyCode
    this.keydownEven = (event: any) => {
      // 如果在输入状态就先按下,且不在监听情况下
      if (this.isFocus && this.curKeyCode === '') return
      //  如果已经按下不许重复触发
      if (this.curKeyCode === event.keyCode) {
        return
      }
      // 判断是否开启监听
      if (this.isMonitorKeyCode) {
        if (event.keyCode !== this.monitorKeyCode) {
          return
        }
      }
      this.curKeyCode = event.keyCode
      this.monitorCallback(1, event)
    }
    this.keyupEven = (event: any) => {
      // 判断是否开启监听
      if (this.isMonitorKeyCode) {
        if (event.keyCode !== this.monitorKeyCode) {
          return
        }
      }
      // 如果在输入状态就先不弹起
      if (this.isFocus) return
      this.curKeyCode = ''
      this.monitorCallback(0, event)
    }
    document.addEventListener('keydown', this.keydownEven, false)
    document.addEventListener('keyup', this.keyupEven, false)
    // 是否获取焦点,方便在输入的时候排除按钮监听
    if (this.isMonitorKeyCode) {
      this.focusEven = (event: any) => {
        if (this.isFocus) return
        this.isFocus = true
      }
      this.blurEven = (event: any) => {
        if (this.isFocus === false) return
        this.isFocus = false
      }
      document.addEventListener('focus', this.focusEven, true)
      document.addEventListener('blur', this.blurEven, true)
    }
  }

  monitorCallback (type: number, event: any) {
    // console.log(type === 1 ? '按下' : '抬起')
  }

  setKeyCode (res: { key: string; code: string; keyCode: number}) {
    storejs.set('FnPttKeyInfo', res)
  }

  getKeyCode () {
    const fnPttKeyInfo = storejs.get('FnPttKeyInfo') || { key: ' ', code: 'Space', keyCode: 32 }
    return fnPttKeyInfo
  }

  removeEvent () {
    this.keydownEven && document.removeEventListener('keydown', this.keydownEven)
    this.keyupEven && document.removeEventListener('keyup', this.keyupEven)
    this.focusEven && document.removeEventListener('focus', this.focusEven)
    this.blurEven && document.removeEventListener('blur', this.blurEven)
  }
}