我創建了一個虛擬鍵盤作爲一個項目來學習,除其他事項外,jQuery的:http://brianfryer.1.ai/virtual-keyboard/index.html如何使用keydown事件設置變量?
當點擊屏幕上的按鍵,其相關的字符添加到文本區域。
然而,當鍵盤按鍵被按下時,什麼也沒有發生 - 關聯的字符應該被添加到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作爲鍵綁定。
謝謝!這當然有助於:-) – brianfryer