简体   繁体   中英

clicking a button with a keyboard

lets say I have a button like this:

<input id="a" type="button" value="A" />

and I want it so that if I press the "a" key on the keyboard, it visually acts as though I am clicking the button with the mouse. Is there a way to do that?

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 65) {
    document.getElementById("a").click();
    // Your function here.
  }
};

for other keycodes refer Keycodes

Have a look at HTML5's globalaccesskey :

http://www.w3schools.com/tags/att_global_accesskey.asp

** EDIT **

Or if you are looking for a pure javascript way, you could try this:

document.onkeypress = textsizer;

function textsizer(e){
var evtobj=window.event? event : e;
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey=String.fromCharCode(unicode);
if (actualkey=="e"){
document.getElementById('a').click();
}
}

This should work: (Assumes JQuery)

$(document).keyup(function (event) {
  if (event.which == 65) { // "A" key
    $('#a').click();
    }
});

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