最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detect if a character or number has been typed - Stack Overflow

programmeradmin6浏览0评论

I would like to set up a home page where pressing any character (lowercase or uppercase) or any number redirects the user to the login page, as the home page itself doesn't have anything to do that requires typing.

My first attempt was this:

document.onkeyup = function() {
  document.location.href = "/login"
}

This works but it works for every key, including cursors, tab, and even caps lock. How can I restrict this function so it only responds to characters and numbers?

I would like to set up a home page where pressing any character (lowercase or uppercase) or any number redirects the user to the login page, as the home page itself doesn't have anything to do that requires typing.

My first attempt was this:

document.onkeyup = function() {
  document.location.href = "/login"
}

This works but it works for every key, including cursors, tab, and even caps lock. How can I restrict this function so it only responds to characters and numbers?

Share Improve this question asked May 24, 2011 at 21:09 sscirrussscirrus 56.8k42 gold badges137 silver badges237 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

When the event occurs, the key code is sent as an event argument. We can use that to determine if a character or number key was pressed. Like this:

document.onkeyup = function(e) {

  if ((e.keyCode >= 65 && e.keyCode <= 90) ||
      (e.keyCode >= 97 && e.keyCode <= 122) ||
      (e.keyCode >= 48 && e.keyCode <= 57)){
      document.location.href = "/login";
  }
};

For reference, the number used above are ASCII codes, you can find the plete list here: http://asciitable./. 48-57 are numbers 0-9, 65-90 are upper case characters, and 97-122 are lower case characters.

You can find a very simple JS Fiddle example here: http://jsfiddle/jpYyg/ . Remember to click inside the "Result" panel (bottom-right one) before pressing any buttons or it won't work!

HTH

<script type="text/javascript">
    document.onkeyup = function (e) {
        var patt =/\w/g;
        var key = String.fromCharCode(e.keyCode);
        if (patt.test(key))
            document.location.href = "/login";
    }
</script>
document.onkeyup = function(event) {
    if (###event.keyCode corresponds to a letter or numeral###)
        document.location.href = "/login";
    else
        event.preventDefault();
}

You can also see the demo for http://api.jquery./keypress/ if you wish to simplify your life with jQuery.

发布评论

评论列表(0)

  1. 暂无评论