【问题标题】:Detecting keyboard button and play sound in vue.js在 vue.js 中检测键盘按钮并播放声音
【发布时间】:2018-05-11 11:21:40
【问题描述】:

下面的代码实际上会在 vue.js 的每个按钮点击时播放声音。

当 DOM 准备好而不是单击按钮时,如何检测键盘按下和播放声音?

例如在输入播放声音v-on:keyup.13="playSound('path/to/mp3')"

Vue 文档主要解释 html 属性,我猜这可能是需要在 JS 中完成的事情。我是 Vue.js 的新手

Event Modifiers 上的 Vue.js 文档

请参阅codepen

new Vue({
  el: '#app',
  data: {
    text: ''
  },
  methods: {
    playSound (sound) {
      if(sound) {
        var audio = new Audio(sound);
        audio.play();
      }
    }
  }
});

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    当您按下一个键时,键盘事件将从active element 触发并向上冒泡。因此,如果您想处理 所有 按键而不管哪个元素具有焦点,那么您需要在代码中手动注册侦听器,例如 document

    new Vue({
      el: '#app',
      created() {
        this.onKeyDown = this.onKeyDown.bind(this);
        document.addEventListener('keydown', this.onKeyDown);
      },
      destroyed() {
        document.removeEventListener('keydown', this.onKeyDown);
      },
      methods: {
        playSound (sound) {
          if(sound) {
            var audio = new Audio(sound);
            audio.play();
          }
        },
        onKeyDown(e) {
          switch (e.keyCode) {
            case 65: this.playSound(sound1); break; // 'a' key
            case 66: this.playSound(sound2); break; // 'b' key
          }
        },
      }
    });
    

    Codepen

    【讨论】:

    • 如何找到按键值?为什么这不起作用? w3schools.com/jsref/…
    • A 的 ASCII 值为 65。keyCode 唯一地表示被按下的键,而不是它将产生的可打印字符(即,aA 都具有相同的密钥代码,因为它是相同的密钥)。在 JavaScript 中处理键盘事件时有很多细微差别,我不会在这里详细说明,但您可以阅读 MDN 上的 KeyboardEvent 以获取更多信息,或者在 StackOverflow 上提问另一个问题。 keypress确实区分可打印字符。
    • 一张便条。这有点慢,因为每个请求都需要下载声音。即使每个声音小于 40 kbs,heroku 上的每个请求也会有 95 毫秒的延迟。
    • 如果您要映射多个按钮实例并且需要每个按钮的特定键的侦听器,那么添加一组开关盒是不是最好的方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多