1、在当前页截获键盘事件,所有按钮均被控制
created () { this.keyDown(); }, beforeDestroy () { this.keyDownReview() }, methods: { //按键恢复 keyDownReview () { document.onkeydown = function (event) { var e = event || window.event; e.returnValue = true; } }, //按钮监听键盘 keyDown () { //监听键盘按钮 document.onkeydown = function (event) { var e = event || window.event; var keyCode = e.keyCode || e.which; switch (keyCode) { case 112://F1 alert('F1') break; case 113://F2 alert('F2') break; case 117://F6 alert('F6') break; case 119://F8 alert('F8') break; case 13://enter alert('enter') break; default: break; } if (e && e.preventDefault) { e.preventDefault(); } else { window.event.returnValue = false; } } }, }
2、单一按钮通过单一键盘键控制,其他不受影响
<el-button type="primary" @click="refresh">刷新(F1)</el-button>
created () { this.keyDown() }, beforeDestroy () { this.keyDownReview() }, methods: { //按键恢复 keyDownReview () { document.onkeydown = function (event) { var e = event || window.event; e.returnValue = true; } }, //键盘按钮截获 keyDown () { document.onkeydown = e => { //112表示F1键 if (e.keyCode === 112) { //F1键后执行刷新方法 this.refresh() //取消原来的后续事件 e.preventDefault() } } }, refresh () { alert('refresh') }, }
3、详细keyCode值列表