简体   繁体   中英

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! button, I want them to just be able to press enter.

How do I assign the Enter key, to that button.

As noted by other devs, you should really look into JavaScript events .

That said, here is an example event that will listen to the document for the 'Enter' keydown event.

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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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