如何使用keydown事件设置变量?

时间:2012-09-19 03:51:16

标签: jquery

我创建了一个虚拟键盘作为项目来学习jQuery:http://brianfryer.1.ai/virtual-keyboard/index.html

单击屏幕上的键时,其关联的字符将添加到textarea。

按下键盘键时,没有任何反应 - 相关字符应添加到textarea。

我遇到的问题是clickedKey变量。将clickedKey设置为静态字符(即'm')将产生所需的结果(字符被添加到textarea),但我不认为为每个键创建一个大的代码块是非常的好主意。

$(document).ready(function() {

    // Find the textarea, and save it to var screen
    var screen = $("#screen > textarea");

    $('li').not('.modifier, .short-key').click(function() {
        // Find the first <span>, get the contents, trim away the whitespace, and save it to var txt
        var txt = $(this).find(':first-child').text().trim();
        // Add the trimmed txt to the textarea
        screen.val(screen.val() + txt);
    });

    var clickedKey = $(document).keydown( function(event){ String.fromCharCode(event.keyCode); });

    KeyboardJS.bind.key(
        // Physical keyboard input
        clickedKey,
        // onDownCallback
        function() {
            // Make the on-screen key flash
            $('#' + clickedKey).addClass('hover');
            // If the textarea has focus...
            if ($('#screen > textarea').is(':focus')) {
                // ...do nothing
            } else {
                // Add the trimmed txt from the first span to the textarea
                var txt = $('.keys').find('#' + clickedKey).children(':first').text().trim();
                screen.val(screen.val() + txt);
            }
        },
        function() {
            // After a key is clicked, remove the .hover class
            setTimeout(function() {
                $('.keys').find('#' + clickedKey).removeClass('hover');
            }, 100);
        }
    );

});

我正在使用keyboard.js进行密钥绑定。

3 个答案:

答案 0 :(得分:1)

Keyboard.js意味着直接与js一起使用。您正在尝试将jQuery事件对象传递给它,这就是它返回错误的原因:

Object [object Object] has no method 'toLowerCase' - Keyboard.js

解决方案是使用javascript来获得keypressed。 我把这个添加到你的头上:http://robertwhurst.github.com/KeyboardJS/demo.js

将此添加到您的身体:<div class="demoReadout"></div>

这对我有用。现在你只需要从那里将事件挂钩到你的jQuery。 希望有所帮助。

答案 1 :(得分:1)

我是KeyboardJS的作者。

通过activeKeys方法按下键可能会有所帮助。这样,您就可以获得我用于特定密钥的确切名称,并且您的绑定将起作用。

clickedKey = KeyboardJS.activeKeys()[0];

答案 2 :(得分:0)

使用我在这里找到的答案(http://stackoverflow.com/a/2819568/1681875),我能够整理以下内容(有效):

// "press" = you used your physical keyboard
// "clicked" = you used your mouse to click the on-screen keyboard

$(document).ready(function() {

// Find the textarea, save it to var screen, and focus the cursor on it
var screen = $("#screen > textarea");
screen.focus();

// Listen for when a (non-modifier, or non-function) key is clicked
$('li').not('.modifier, .short-key').click(function() {

    // Find the first <span>, get the contents, trim away the whitespace, and save it to var txt
    var character = $(this).find(':first-child').text().trim();

    // Extend jQuery to insert characters at the caret
    jQuery.fn.extend({
        insertAtCaret: function(character){
            return this.each(function(i) {
                if (document.selection) {
                    //For browsers like Internet Explorer
                    this.focus();
                    sel = document.selection.createRange();
                    sel.text = character;
                    this.focus();
                }
                else if (this.selectionStart || this.selectionStart == '0') {
                    //For browsers like Firefox and Webkit based
                    var startPos = this.selectionStart;
                    var endPos = this.selectionEnd;
                    var scrollTop = this.scrollTop;
                    this.value = this.value.substring(0, startPos)+character+this.value.substring(endPos,this.value.length);
                    this.focus();
                    this.selectionStart = startPos + character.length;
                    this.selectionEnd = startPos + character.length;
                    this.scrollTop = scrollTop;
                } else {
                    this.value += character;
                    this.focus();
                }
            })
        }
    });

    // Insert characters in the textarea at the current caret
    screen.insertAtCaret(character);
});

$(document).on({
    // Do this when a key is pressed
    'keydown': function(event){
        // Get the value of the key being pressed and make sure it's lower case
        key = (String.fromCharCode(event.keyCode)).toLowerCase();
        // Make the on-screen key flash for 100ms
        $('#' + key).addClass('hover');
        // Focus on the textarea
        $('#screen > textarea').focus();
    },
    // Do this when a key is let go
    'keyup': function(event) {
        // Get the value of the key being pressed
        key = String.fromCharCode(event.keyCode).toLowerCase();
        // After a key is clicked, remove the .hover class
        $('#' + key).removeClass('hover').delay(100);
     }
});

});