微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 检测可打印的键

我需要检测刚被按下的键是一个可打印的键,如字符,可能有重音,数字,空格,标点符号等,还是不可打印的键,如ENTER,TAB或DELETE.

有没有可靠的方式来做这个Javascript,除了列出所有不可打印的键,希望不要忘记一些?

解决方法

我昨天回答了一个 similar question.请注意,您必须使用按键事件与任何字符相关; keydown不会做.

我会认为Enter是可打印的,顺便说一下,这个功能认为它是.如果您不同意,您可以修改它,以将该事件的哪个或keyCode属性设置为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!");
    }
});

原文地址:https://www.jb51.cc/js/154233.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐