开发者

Add An Even listener For any letter keys pressed?

开发者 https://www.devze.com 2023-01-25 07:06 出处:网络
I am wondering how to create an event listener, so that when any of the character keys are pressed a form pops up and the first input is in focus and is receiving the input, sort of like the just type

I am wondering how to create an event listener, so that when any of the character keys are pressed a form pops up and the first input is in focus and is receiving the input, sort of like the just type search style for the webOS 2.0 operating system, but for a contact for开发者_如何学Pythonm. Is there anyway to do so? In case your not familiar here is a link to the webos just type feature

http://www.youtube.com/watch?v=ixPsB7-tVGo


I don't know if you can only subscribe to letter keys.

Your best bet would be to use jQuery to subscribe to .keydown() / .keyup() and check the keycode of the event to see which letter it is. If it's not a letter, don't do anything.

Like this:

$('#target').keydown(function(event) {
  if (event.keyCode >= 65 && event.keyCode <= 90) { // if a letter pressed
     // play that funky music.  
  }
});

More on $.keydown.

List of key codes.


Use the keypress event for anything character related. keydown and keyup cannot be used reliably for this purpose. The following is adapted from my answer to a related recent question:

function isCharacterKeyPress(evt) {
    if (typeof evt.which == "undefined") {
        // This is IE, which only fires keypress events for printable keys
        return true;
    } else if (typeof evt.which == "number" && evt.which > 0) {
        // In other browsers except old versions of WebKit, evt.which is
        // only greater than zero if the keypress is a printable key.
        // We need to filter out backspace and ctrl/alt/meta key combinations
        return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
    }
    return false;
}

var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
    evt = evt || window.event;

    if (isCharacterKeyPress(evt)) {
        // Do your stuff here
        alert("Character!");
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号