键盘支持总结

由 漆黑菌 于 2021年06月16日 发布

tabindex

  1. -1 只能通过js或鼠标focus
  2. 0 键盘tab,js和鼠标都能focus
  3. 当tabindex≥1的时候,按tab时会按照数字从小到大切换。但是0是排在其他数字之后的。比如有0、1、2、3,那么顺序是1-2-3-0

给svg图标组件添加类似button的行为

button可以被tab选中,选中后键盘输入enter空格都会触发click效果。disabledclick事件不会被触发。

被tab选中可以通过tabindex="0"来模拟。

键盘操作触发click事件,由于svg元素没有原生的.click()方法,所以需要使用e.target.dispatchEvent(new Event('click', { bubbles: true }));来模拟。

disabled状态使用监听click事件并执行e.stopImmediatePropagation();来取消click事件。

给dom添加全局hotkey

body就算没加tabindex并被选中也可以监听到keyup,keydown事件。所以理论上在页面全局初始化后监听body的相关事件,并扫一遍dom中有指定自定义属性的dom(理论上css选择器就可以做到),就可以模拟全局快捷键了。

  <input
    hotkey="/"
    autofocus
  >

  mounted() {
    this.hotKeyDom = [...document.querySelectorAll('[hotkey]')];
    this.hotKeyDomMap = this.hotKeyDom.map((dom) => ({
        hotkey: dom.getAttribute('hotkey'),
        dom,
      }));
    document.body.addEventListener('keyup', this.globalHotkey);
  },
  beforeDestroy() {
    document.body.removeEventListener('keyup', this.globalHotkey);
  },
  methods: {
    globalHotkey({ key }) {
      this.hotKeyDomMap.forEach(({ hotkey, dom }) => {
        if (hotkey.includes(key)) {
          dom.focus();
        }
      });
    },
  }