当前位置:首页 > 编程笔记 > 正文
已解决

全局的键盘监听事件

来自网友在路上 193893提问 提问时间:2023-09-20 07:13:16阅读次数: 93

最佳答案 问答题库938位专家为你答疑解惑

一、设定全局键盘监听事件 

放在vue 的created()或者mounted ()中,可对整个文档进行键盘事件监听。

new Vue({  created() {  window.addEventListener('keydown', this.handleKeydown);  },  beforeDestroy() {  window.removeEventListener('keydown', this.handleKeydown);  },  methods: {  handleKeydown(e) {  console.log('keydown event triggered', e);  }  }  
}).$mount('#app');

 或者

 // 监听键盘事件document.addEventListener('keydown', function (event) {console.log('按下的键: ', event.key)// 根据不同的键执行不同的操作switch (event.key) {case 'Delete':self.delEl()// 执行 a 键对应的操作breakcase 'Backspace':self.delEl()// 执行 b 键对应的操作break// 其他键...default:break}})

二、特定的div中禁用全局的键盘事件

<template>  <div @keydown.stop>  <!-- 键盘事件将不会冒泡到该div的父元素 -->  </div>  
</template>

关键:@keydown.stop

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"全局的键盘监听事件":http://eshow365.cn/6-9853-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!