javascript - Javascript 游戏 GUI 的快捷键

标签 javascript jquery button hotkeys

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

首先,我尝试使用 JSQuery 热键脚本和 .bind 命令,但这似乎非常耗时,因为我必须将每个 .onclick 重新编码为热键,即使使用取消绑定(bind),它也会被触发每个事件都与脚本上的键相关联。

我觉得最好的方法是,如果我可以将按键编码到 gui,即,如果当您按下“1”时,它会激活按钮 1 的 .onclick,这样热键将是静态的(除了当按钮被禁用时),但我不知道该怎么做。我刚刚使用了 html 按钮(即 input type="button"value=""disabled="disabled"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();   
});
});
}

由于按钮一执行的代码在功能之间发生变化,热键的作用也是如此,这是我使用 JQuery 库代码时遇到的问题。

最佳答案

当按下一个键时,事件 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

关于javascript - Javascript 游戏 GUI 的快捷键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32437158/

相关文章:

html - 在 html 按钮中包装一个 react-router 链接

Javascript 函数不接受变量作为参数

jquery - 如何在 WebKit 浏览器中使用 jQuery .focus()

android - 与 Xcode 中一样,Android 中按下按钮的背景变化

javascript - 使用 Javascript 从 JSON 中获取数据

javascript - 将对象中的数据类型从 int 转换为 string

java - 如何将gif放在Button的背景中?安卓

javascript - 替换 img 路径 jquery

javascript - jspdf 的 addImage() 函数的确切参数列表及其描述是什么?

java - 从 GWT 调用 java