用JavaScript获取输入的特殊字符

Web开发时可能经常会用到在keyPress时获得输入的字符。String.fromCharCode()可以来实现这个,不过这个函数在你使用Shift键来输入特殊字符时就不管用了,需要改造一下,这个帖子给出了改造的方法,经测试在各种主流浏览器均正常。

<html>
<head>
<title >mapKeyPressToActualCharacter test</title>
<script language="javascript" type="text/javascript">
    function onKeyPress() {
 
        var e = window.event || e;
        var keyCode = e.keyCode;
 
        if (keyCode == 8) {
            this.criteria.value = this.criteria.value.substring(
                    0, this.criteria.value.length - 1);
        }
        else {
            this.criteria.value
                += mapKeyPressToActualCharacter(event.shiftKey, keyCode);
        }
 
    }
 
    function mapKeyPressToActualCharacter(isShiftKey, characterCode) {
        if (characterCode === 27
            || characterCode === 8
            || characterCode === 9
            || characterCode === 20
            || characterCode === 16
            || characterCode === 17
            || characterCode === 91
            || characterCode === 13
            || characterCode === 92
            || characterCode === 18) {
            return false;
        }
        if (typeof isShiftKey != "boolean" || typeof characterCode != "number") {
            return false;
        }
        var characterMap = [];
        characterMap[192] = "~";
        characterMap[49] = "!";
        characterMap[50] = "@";
        characterMap[51] = "#";
        characterMap[52] = "$";
        characterMap[53] = "%";
        characterMap[54] = "^";
        characterMap[55] = "&";
        characterMap[56] = "*";
        characterMap[57] = "(";
        characterMap[48] = ")";
        characterMap[109] = "_";
        characterMap[107] = "+";
        characterMap[219] = "{";
        characterMap[221] = "}";
        characterMap[220] = "|";
        characterMap[59] = ":";
        characterMap[222] = "\"";
        characterMap[188] = "<";
        characterMap[190] = ">";
        characterMap[191] = "?";
        characterMap[32] = " ";
        var character = "";
        if (isShiftKey) {
            if (characterCode >= 65 && characterCode <= 90) {
                character = String.fromCharCode(characterCode);
            } else {
                character = characterMap[characterCode];
            }
        } else {
            if (characterCode >= 65 && characterCode <= 90) {
                character = String.fromCharCode(characterCode).toLowerCase();
            } else {
                character = String.fromCharCode(characterCode);
            }
        }
        return character;
    }
 
</script>
 
</head>
<body>
    <input name="test" type="text" onkeypress="onKeyPress();"/>
</body>
</html>

 

测试结果截图,在Firefox, Chrome and IE.和Safari下均通过:

 

TestResult


Related Posts Plugin for WordPress, Blogger...