Javascript鍵盤事件的keyChar

Javascript的鍵盤事件keydown, keyup,  keypress的event對象中,keyCode !=  keyChar,網上有很多人提供瞭keyCode到keyChar的對照表。於是,根據對照表,產生瞭如下工具函數,隻需要把event對象作為參數傳進去,就能夠得到keyChar瞭,如果keyCode沒有對應的字符,那返回的就是'\0'。
window.keyChar = (function () {
    var ssss = "";
    var SSSS = "";
 
    // M和m隻是標尺, ssss和SSSS變量長度是為瞭對齊標尺
    var M = "0         1         2         3         4         ";
    var m = "01234567890123456789012345678901234567890123456789";
 
    // 不帶shift的碼表
    ssss += "                                                01";
    ssss += "23456789       abcdefghijklmnopqrstuvwxyz     0123";
    ssss += "456789*+ -./                                      ";
    ssss += "                                     ;=.-,/`      ";
    ssss += "                   [ ]'                           ";
 
    // 帶shift的碼表
    SSSS += "                                                )!";
    SSSS += "@#$%^&*(       ABCDEFGHIJKLMNOPQRSTUVWXYZ     0123";
    SSSS += "456789*+ -./                                      ";
    SSSS += "                                     :+>_<?~      ";
    SSSS += "                   {|}                            ";
 
    // 將碼表拆成字符數組
    var t = ssss.split("");
    var T = SSSS.split("");
 
    // 將所有空格替換成空字符
    var nullChar = String.fromCharCode(0);
    for (var i = 0; i < t.length; i++) {
        (t[i] === " ") && (t[i] = nullChar);
        (T[i] === " ") && (T[i] = nullChar);
    }
 
    // 幾個需要轉義的字符,放在表裡會影響排版,所以單獨處理
    t[9] = "\t";
    t[13] = "\n";
    t[32] = " ";
    t[220] = "\\";
 
    T[32] = " ";
    T[222] = '"';
 
    return function (event, isCheckShift) {
        if (typeof isCheckShift === "undefined") { isCheckShift = true; }
        if (!!isCheckShift && event.shiftKey) {
            return T[event.keyCode];
        } else {
            return t[event.keyCode];
        }
    };
})();
 
作者“邊城客棧 學海無涯”

You May Also Like