Javascript游戏GUI

时间:2015-09-07 11:06:47

标签: javascript jquery button hotkeys

我一直在制作一个简单的基于javascript的OOP文本游戏,该游戏使用与按钮.onclick事件相关联的字符串替换和变量调整。我被要求添加热键以便于访问,而且我一直在努力解决这个问题。

首先,我尝试使用JSQuery热键脚本和.bind命令,但这似乎非常耗时,因为我必须将每个.onclick重新编码为热键,即使使用unbind,它也是解除与剧本上的关键字相关的每个事件。

我觉得最好的方法就是如果我可以将键编码到gui,即当你按下" 1"时,它激活按钮1的按键,就像热键一样将是静态的(除非按钮被禁用),但我不知道该怎么做。我刚刚使用了html按钮,(即输入类型="按钮"值=""禁用="禁用" id =" button1"),我怀疑我需要更复杂的东西?

预先感谢您提供任何帮助,谷歌一直没用。

[编辑 - 代码的一般描述]

游戏的工作方式非常简单,通过调用函数作为具有不同文本/按钮的新事件(以及与这些按钮相关联的不同onclick事件)。例如,开始屏幕代码为:

function startScreen() {
$(document).ready(function () {
$('#text').html("Game title and info");
$('#button1').val("Start Game");
$('#button1').attr("disabled", false);
$("#button1").one("click", function () {
textClear();
buttonClear();
nameScreen();
});

$("#button2").val("Load Game");
$('#button2').attr("disabled", false);
$("#button2").one("click", function () {
textClear();
buttonClear();  
loadData();
});

$("#button6").val("Settings");
$('#button6').attr("disabled", false);
$("#button6").one("click", function () {
textClear();
buttonClear();
settingsScreen();   
});
});
}

由于按钮1执行的代码在函数之间发生了变化,热键的作用也是如此,这是我使用JQuery库代码的问题。

1 个答案:

答案 0 :(得分:2)

按下某个键后,会触发事件onkeypress。此事件提供了一些值,如:

  • keyCode
  • charCode
  • which

所以你可以这样做:

window.onkeypress = function (event) {
    // the keyCode value for the key 1 is 49, for the key 2 is 50
    if (event.keyCode == 49) {
        // execute the same code as clicking the button 1
        console.log("The key 1 was pressed.");
    } else if (event.keyCode == 50) {
        // execute the same code as clicking the button 2
        console.log("The key 2 was pressed.");
    }
};

现在,当用户访问您的网站时,他可以按键盘上的键1或2,并点击相同的逻辑,如点击“1”和“2”按钮(类似于<input id="button1">)留下老鼠的味道。

如果你真的有很多热键,那么键入也会很乏味,但是如果不知道你的代码,我几乎无法给你一个完整的解决方案。我希望我的回答可以让你知道如何进一步。

编辑:

进一步阅读该主题: http://unixpapa.com/js/key.html