VUE使用document.onkeydown键盘的监听与移除
在项目中 偶尔会使用到监听键盘事件,当只写了调用键盘事件时,切换到其他页面的时候,发现仍会触发键盘事件,如果需求时不需要全局监听的话,就需要写一个 取消键盘监听事件//取消键盘监听事件document.onkeydown = null实例:在这里插入代码片mounted(){this.keyDown() // 监听键盘},destroyed(){//取消键盘监听事件document.onkeydo
·
在项目中 偶尔会使用到监听键盘事件,当只写了调用键盘事件时,切换到其他页面的时候,发现仍会触发键盘事件,如果需求时不需要全局监听的话,就需要写一个 取消键盘监听事件
//取消键盘监听事件
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("键盘按键--右箭头" )
}
}
}
}
更多推荐
已为社区贡献3条内容
所有评论(0)