简体   繁体   English

如何将键盘笔划分配给按钮?

[英]How can i assign a Keyboard stroke to a button?

I have a text adventure game where the user needs to enter commands to proceed through the game.我有一个文本冒险游戏,用户需要输入命令才能继续游戏。 so instead of them having to click on the GO!所以他们不必点击GO! button, I want them to just be able to press enter.按钮,我希望他们能够按回车键。

How do I assign the Enter key, to that button.如何将 Enter 键分配给该按钮。

As noted by other devs, you should really look into JavaScript events .正如其他开发人员所指出的,您应该真正研究JavaScript 事件

That said, here is an example event that will listen to the document for the 'Enter' keydown event.也就是说,这里是一个示例事件,它将侦听“Enter”keydown 事件的文档。

document.addEventListener("keydown", function (e) {
    e.preventDefault();
    if (e.key === "Enter") {
        console.log('You pressed enter.')
    }
});

You can programmatically fire click event on a element.您可以以编程方式触发元素上的点击事件。 In snippet example below we add a " Keyup EventListener " to window object.在下面的代码片段示例中,我们向window对象添加了一个“ Keyup EventListener ”。 In order to make enter captured, you need to first click on somewhere on snippet preview.为了使输入被捕获,您需要首先单击代码段预览中的某个位置。 Because when you click on preview, you will be focused on preview document.因为当您单击预览时,您将专注于预览文档。

 window.addEventListener('keyup', function(e) { if (e.which == 13) { e.preventDefault(); document.getElementById('go-button').click(); } })
 #scene { width: 500px; height: 300px; background-color: #999; display: flex; justify-content: center; align-items: center; } #go-button { cursor: pointer; outline: none; border: none; width: 100px; height: 100px; background-color: cornflowerblue; color: #eee; font-size: x-large; border-radius: 55%; } #go-button span{ font-size: small; } #go-button:hover { background-color: #729dee; }
 <div id="scene"> <button onclick="alert('Go clicked')" id="go-button" type="button"> Go! <br> <span> [Enter] </span> </button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM