Javascript:keydown上的触发按钮

时间:2015-03-29 19:07:35

标签: javascript jquery keydown

我正在构建一个音乐电子学习的东西,并希望使用键盘触发输入按钮,这将播放指定的音符。就像一架钢琴!除了这个之外会让你的耳朵流血,但这就是重点。

onclick()本身在手动按下按钮时有效,但绑定到键盘很困难。

HTML:

<input type="button" id="pgC" value="C" onClick="pgC()">
<input type="button" id="pgCsharp" value="C#" onClick="pgCsharp()">

绑定到键盘的脚本:

$(function() {
$(document).keydown(function(e) {
    switch (e.keyCode) {
    case 65:
        $('#pgC')[0].onclick();
        break;
    case 87:
        $('#pgCsharp')[0].onclick();
        break;
    }
 });
});

我试图从中修改:Binding Keyboard to Onclick Event

我的理解是$('#pgC')[0].onclick();应找到指定的id,并根据按下的键触发onclick,在本例中为小写“a”。

非常感谢任何和所有帮助! :d

1 个答案:

答案 0 :(得分:0)

以下是处理简单案例的答案,但您需要考虑其他内容,例如:如果用户想要演奏和弦等,该怎么办?

您可以在此处查看简单演示并根据需要进行编辑,http://plnkr.co/edit/ZfcHdM?p=preview

然而,在你现在开始前行之前,只需环顾GitHub或网络。我感觉有人已经完成了你想要完成的任务。

这是一个片段。

(function() {
  var KeyboardSimulator = (function () {
    function KeyboardSimulator() {
    }

    KeyboardSimulator.prototype.keyPressed = function (key) {
        // Add some logic to check if the particular key is registered.
        console.log('The musician pressed the "' + key + '" key.');
    };

    return KeyboardSimulator;
  })();

  $(document).ready(function() {
    var simulator = Object.create(KeyboardSimulator.prototype);
    var intrumentSimulatorContext = $('#instrumentSimulator');

    intrumentSimulatorContext.on('click', '.key', function(e) {
      var key = $(this).val();

      e.preventDefault();
      simulator.keyPressed(key);
    });

    $(document.body).on('keydown', function(e) {
      var key = String.fromCharCode(e.keyCode).toUpperCase(),
        keyMap = {
          // keyboard key -> musical note
          'A': 'C',
          'W': 'CSharp',
          'S': 'D'
        }

      if (key in keyMap) {
        $('#pg' + keyMap[key]).trigger('click');
      }

    })
  });
})();