一开始采用的是这种做法:监听keydown事件,然后根据键值禁用默认事件,发现不可行,源码如下

 mounted () {
    window.addEventListener('keydown', this.onClick)
}
  onClick (val) {
      console.log('按下' + val.key)
      console.log('keycode:' + val.keyCode)
      console.log('thiscode:' + this.code)
      if (val.keyCode === 9) {
        console.log('tabfalse13')
        val.keyCode = 0
        val.returnValue = false
        val.which = 0
        val.preventDefault()
        val.stopPropagation()
        val.cancelBubble = true
        window.event.keyCode = 0
        window.event.returnValue = false
        window.event.which = 0
        window.event.preventDefault()
        window.event.stopPropagation()
        window.event.cancelBubble = true
        return false
      }
}

原因可能是因为这里传入的val并不是原键盘事件,所以采取下面的方法发现是可以的

window.addEventListener('keydown', event => {
      console.log('按下' + event.key)
      console.log('keycode:' + event.keyCode)
      console.log('thiscode:' + this.code)
      if (event.keyCode === 9) {
        console.log('tabfalse13')
        event.preventDefault()
      }
}

然后记得离开页面要销毁监听

 destroyed () {
   
    window.removeEventListener('keydown', event => {
      console.log(event.value)
      event.preventDefault()
    })

这样的话按下tab键就不会在浏览器内切换了,只是有输出

Logo

前往低代码交流专区

更多推荐