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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...