【问题标题】:How to decode character pressed from jQuery's keydown()'s event handler如何解码从 jQuery 的 keydown() 事件处理程序按下的字符
【发布时间】:2017-05-24 21:17:35
【问题描述】:

我需要确定在 jQuery 的 keydown 函数调用的处理程序中将哪个字符输入到文本字段中。 key.which 只给了我键码,但我需要弄清楚 key 代表哪个 ASCII 字符。我该怎么做?

【问题讨论】:

    标签: jquery event-handling character keydown


    【解决方案1】:

    keyPress 事件是您需要获取输入的字符。 (请参阅下面的 keydown 事件解决方法)。

    keydownkeyup 提供了一个代码,指示按下了哪个键,而keypress 指示输入了哪个字符。

    使用jQuery e.which 可以获得键码,使用String.fromCharCode 可以获得被按下的特定字符(包括shiftKey)。

    演示: http://jsfiddle.net/9TyzP/3

    代码:

    element.on ('keypress', function (e) {
        console.log(String.fromCharCode(e.which));
    })
    

    注意我说的是 jQuery 的e.which,因为不同的浏览器使用不同的属性来存储这些信息。 jQuery 标准化了 .which 属性,因此您可以可靠地使用它来检索关键代码。

    keydown 的解决方法

    但是,您可以编写一个简单的解决方法来让按下的字符在keydown.. 上工作。解决方法是创建一个对象,其键为 charCode 而不按 shift 键,值是 shift 键。

    注意:正如@Sajjan Sarkar 所指出的,从不同浏览器返回的e.which 键码值存在一些差异。 Read more here

    更新了 DEMO 代码以规范跨浏览器的 keyCode 值。在 IE 8、FF 和 Chrome 中测试和验证。

    下面的完整代码和更新的 DEMO: http://jsfiddle.net/S2dyB/17/

    $(function() {
    
        var _to_ascii = {
            '188': '44',
            '109': '45',
            '190': '46',
            '191': '47',
            '192': '96',
            '220': '92',
            '222': '39',
            '221': '93',
            '219': '91',
            '173': '45',
            '187': '61', //IE Key codes
            '186': '59', //IE Key codes
            '189': '45'  //IE Key codes
        }
    
        var shiftUps = {
            "96": "~",
            "49": "!",
            "50": "@",
            "51": "#",
            "52": "$",
            "53": "%",
            "54": "^",
            "55": "&",
            "56": "*",
            "57": "(",
            "48": ")",
            "45": "_",
            "61": "+",
            "91": "{",
            "93": "}",
            "92": "|",
            "59": ":",
            "39": "\"",
            "44": "<",
            "46": ">",
            "47": "?"
        };
    
        $(element).on('keydown', function(e) {
            var c = e.which;
    
            //normalize keyCode 
            if (_to_ascii.hasOwnProperty(c)) {
                c = _to_ascii[c];
            }
    
            if (!e.shiftKey && (c >= 65 && c <= 90)) {
                c = String.fromCharCode(c + 32);
            } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
                //get shifted keyCode value
                c = shiftUps[c];
            } else {
                c = String.fromCharCode(c);
            }
    
            //$(element).val(c);
        }).on('keypress', function(e) {
            //$(element).val(String.fromCharCode(e.which));
        });    
    });
    

    更多关于键盘事件 --

    keydown、keypress 和 keyup 事件在用户按下某个键时触发。

    keydown 当用户按下某个键时触发。它在用户按住键时重复。

    keypress 在插入实际字符时触发,例如文本输入。它在用户按住键时重复。

    keyup在用户释放一个键时触发,在该键的默认操作已经执行之后。

    当第一次按下某个键时,会发送keydown 事件。如果键不是修饰键,则发送keypress 事件。当用户释放按键时,发送keyup事件。

    当一个键被按下并按住时,它开始自动重复。这会导致类似以下事件的一系列事件被分派:

    keydown
    keypress
    keydown
    keypress
    <<repeating until the user releases the key>>
    keyup
    

    演示: http://jsfiddle.net/9TyzP/1/

    keyup、keydown vs keypress

    keydown 和 keyup 事件表示按键被按下或释放,而 keypress 事件表示正在输入一个字符。

    演示: http://jsfiddle.net/9TyzP/

    参考资料:

    1. https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent

    2. http://www.quirksmode.org/dom/events/keys.html

    3. http://unixpapa.com/js/key.html

    【讨论】:

    • 这看起来是一个很好的规范答案,将等待几天,以便在授予之前获得更多曝光
    • 是的,但由于“keypress 事件未包含在任何官方规范中,因此使用它时遇到的实际行为可能因浏览器、浏览器版本和平台而异。” src:api.jquery.com/keypress AFAIK,你无法在 keydown 中获取 ASCII 值,你只能在 keyup 或 keypress 中获取它,正如上面的人指出的那样。
    • @SajjanSarkar 不正确.. 你在keydown/keyup/keypress 上得到keyCode (e.which)。如果你想要 ASCII 字符,那么你可以使用String.fromCharCode 函数。你没有得到keyup/keypress中的字符。
    • @Vega 是也不是,试试说 Console.log(String.fromCharCode(e.which)) 看看你得到的分号和冒号。
    • @Vega 这是一个不错的方法,但事实是,当我按冒号 (shift+;) 时,我希望代码给我“:”而不是“º:”但你的答案仍然是最好的一个周围..
    【解决方案2】:

    对于字符输入,建议您使用keypress(),它将报告所按下字符的实际ASCII码。它会自动处理字母大小写,并忽略非字符压力。无论哪种情况,您都可以使用 fromCharCode() 转换为字符串表示形式。例如

    var c = String.fromCharCode(e.which) // or e.keyCode
    

    请记住,对于keydown()keyup(),您必须使用e.shiftKey 状态来跟踪案例。

    【讨论】:

    • 哈哈.. 出于某种原因,浏览器在按下逗号时会返回 188,但是当我们将 188 转换为 char 时,它会以 ¼ 的形式出现。有趣的是,当我们将 44 转换为 char 时,浏览器会将其理解为逗号!
    • 我相信它在旧版本的 jQuery 中返回 1/4。在 1.4.2 中已修复。它为我返回逗号
    • hmm 这不考虑 e.shiftKey
    • 我投票支持 keypress - 它接收国际键盘布局的正确字符,不像 keydown 将所有内容转换为单字节字符。
    • 哦,所以String 不是变量... :((
    【解决方案3】:

    我这样做。如果值不是数字,它将忽略按键。 似乎没有任何问题...

        $("input").on("keypress", function(e) {
            if(!jQuery.isNumeric(String.fromCharCode(e.which)))
                return false;
        });
    

    【讨论】:

      【解决方案4】:

      Selvakumar Arumugam 的答案对我来说就像一个魅力......直到我测试小键盘。所以这里有一个小更新:

       $(document).on('keydown', function(e) {
          var c = e.which;
      
          if (_to_ascii.hasOwnProperty(c)) {
              c = _to_ascii[c];
          }
      
          if (!e.shiftKey && (c >= 65 && c <= 90)) {
              c = String.fromCharCode(c + 32);
          } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
              c = shiftUps[c];
          } else if (96 <= c && c <= 105) {
              c = String.fromCharCode(c - 48);
          }else {
              c = String.fromCharCode(c);
          }
      
          $kd.val(c);
      })
      

      http://jsfiddle.net/S2dyB/78/

      【讨论】:

        【解决方案5】:

        我创建并使用上述 javascript 类将 gr 转换为 en 字符。它可以用于更多语言。它使用 JQuery 来更改用户按下的值。

        var CharMapper = function (selector) {
            this.getLanguageMapper = function (languageSource, languageTarget) {
                // Check if the map is already defined.
                if (typeof langugageCharMap === "undefined") {
                    langugageCharMap = {};
                }
                if (typeof langugageCharMap[languageSource] === "undefined") {
                    langugageCharMap[languageSource] = {};
                }
        
                // Initialize or get the language mapper.
                if (typeof langugageCharMap[languageSource][languageTarget] === "undefined") {
                    switch (languageSource) {
                        case "GR":
                            switch (languageTarget) {
                                case "EN":
                                    langugageCharMap[languageSource][languageTarget] = {
                                        "α": "a", "ά": "a", "β": "b", "γ": "g", "δ": "d", "ε": "e", "έ": "e", "ζ": "z", "η": "h", "ή": "h", "θ": "th", "ι": "i", "ί": "i", "ϊ": "i", "ΐ": "i", "κ": "k", "λ": "l", "μ": "m", "ν": "n", "ξ": "ks", "ο": "o", "ό": "o", "π": "p", "ρ": "r", "σ": "s", "ς": "s", "τ": "t", "υ": "y", "ύ": "y", "ϋ": "y", "ΰ": "y", "φ": "f", "χ": "x", "ψ": "ps", "ω": "o", "ώ": "o", "Α": "A", "Ά": "A", "Β": "B", "Γ": "G", "Δ": "D", "Ε": "E", "Έ": "E", "Ζ": "Z", "Η": "H", "Ή": "H", "Θ": "TH", "Ι": "I", "Ί": "I", "Ϊ": "I", "Κ": "K", "Λ": "L", "Μ": "M", "Ν": "N", "Ξ": "KS", "Ο": "O", "Ό": "O", "Π": "P", "Ρ": "R", "Σ": "S", "Τ": "T", "Υ": "Y", "Ύ": "Y", "Ϋ": "Y", "Φ": "F", "Χ": "X", "Ψ": "PS", "Ω": "O", "Ώ": "O"
                                    };
                                    break;
                                case "GR":
                                default:
                                    throw "Language(" + languageTarget + ") is not supported as target for Language(" + languageSource + ").";
                            }
                            break;
                        case "EN":
                        default:
                            throw "Language(" + languageSource + ") is not supported as source.";
                    }
                }
        
                return langugageCharMap[languageSource][languageTarget];
            };
            // Check the existance of the attribute.
            var items = $(selector).find("*[data-mapkey]");
            if (items.length === 0) {
                return;
            }
        
            // For each item.
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
        
                // Get the source and target language.
                var languages = $(item).attr("data-mapkey");
                var languageSource = languages.split("_")[0];
                var languageTarget = languages.split("_")[1];
        
                // Add the event listener.
                var self = this;
                $(item).keypress(function (event) {
                    event.stopPropagation();
                    // Get the mapper to use.
                    var mapper = self.getLanguageMapper(languageSource, languageTarget);
                    // Get the key pressed.
                    var keyPressed = String.fromCharCode(event.which);
                    // Get the key to set. In case it doesn't exist in the mapper, get the key pressed.
                    var keyToSet = mapper[keyPressed] || keyPressed;
                    // Set the key to the dom.
                    this.value = this.value + keyToSet;
        
                    // Do not propagate.
                    return false;
                });
            }
        };
        

        例子,

        <input type="text" data-mapkey="GR_EN" />
        <script type="text/javascript">
            new CharMapper("body");
        </script>
        

        【讨论】:

          猜你喜欢
          • 2011-01-09
          • 1970-01-01
          • 2013-04-18
          • 2022-09-26
          • 1970-01-01
          • 2011-10-12
          • 1970-01-01
          • 1970-01-01
          • 2014-09-10
          相关资源
          最近更新 更多