检测可打印键 [英] Detect printable keys

查看:62
本文介绍了检测可打印键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测刚刚按下的键是可打印键,例如字符(可能带有重音符号),数字,空格,标点符号等,还是不可打印键,例如ENTER,TAB或删除.

I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DELETE.

除了列出所有不可打印的键并希望不要忘记某些键之外,是否有一种可靠的方法可以用Javascript做到这一点?

Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?

推荐答案

我回答了

I answered a similar question yesterday. Note that you have to use the keypress event for anything character-related; keydown won't do.

顺便说一句,我认为 Enter 是可打印的,并且此函数认为它是可以打印的.如果您不同意,则可以对其进行修改,以将事件的whichkeyCode属性设置为13来过滤按键.

I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which or keyCode property of the event set to 13.

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!");
    }
});

这篇关于检测可打印键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆