在项目中 偶尔会使用到监听键盘事件,当只写了调用键盘事件时,切换到其他页面的时候,发现仍会触发键盘事件,如果需求时不需要全局监听的话,就需要写一个 取消键盘监听事件

 //取消键盘监听事件
        document.onkeydown = null

实例:

在这里插入代码片
	mounted(){
        this.keyDown() // 监听键盘
    },
    destroyed(){
      //取消键盘监听事件
        document.onkeydown = null
    },
    methods:{
     // 监听键盘
        keyDown() {
            document.onkeydown =  (e) => {
                //事件对象兼容
                let e1 = e || event || window.event || arguments.callee.caller.arguments[0]
                console.log("键盘按键==",e1,e1.keyCode )
                //键盘按键判断:左箭头-37;上箭头-38;右箭头-39;下箭头-40
                //左
                if(e1 && e1.keyCode == 37 ){
                   console.log("键盘按键--左箭头" )
                }else if(e1 && e1.keyCode == 39 ){
                       console.log("键盘按键--右箭头" )
                }
             }
         }
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐