特殊字符在OSX上的html keypress事件上不起作用 [英] Special characters not working on html keypress events on OSX

查看:128
本文介绍了特殊字符在OSX上的html keypress事件上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 < html> 
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8/>
< script src =js / jquery.js>< / script>
< / head>
< body>
< script>
$('body')。keypress(function(e){
console.log('char:',String.fromCharCode(e.keyCode));
});
< / script>
< / body>
< / html>尝试输入特殊字符,例如

c $ c>会打印 aeiou

注意jQuery keypress 的文档说:注意:作为 keypress 事件不受任何官方规范的约束,在浏览器,浏览器版本和平台上使用时遇到的实际行为可能会有所不同。 它还说:要确定输入了哪个字符,请检查传递给处理函数的事件对象。虽然浏览器使用不同的属性来存储这些信息,但jQuery对属性进行了规范化处理,以便您可以可靠地使用它来检索字符代码。



至少在Windows中,使用 e.which 在浏览器中给出一致的结果,而 e.keyCode 不。它产生输入的字符,例如á当我按下急键(')然后按A键时。如果在OSX中没有发生这种情况,那么解释可能是处理密钥的系统级差异;您可能需要检查是否可以更成功地使用 keydown keyup (它们应指示按下的键,并且你需要在你的程序逻辑中从它们中推导出字符)。

The following page won't work as expected.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <script src="js/jquery.js"></script>
    </head>
    <body>
        <script>
            $('body').keypress(function(e){
                console.log('char: ',String.fromCharCode(e.keyCode));
            });
        </script>
    </body>
</html>

Trying to type special characters such as á é í ó ú will print a e i o u instead.

解决方案

Note that jQuery documentation of keypress says: "Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms." It also says: "To determine which character was entered, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the character code."

At least on Windows, using e.which gives consistent results in browsers, whereas e.keyCode does not. And it yields the character entered, e.g. á when I press the acute key (´) and then the A key. If this does not happen in OSX, then the explanation is probably system-level difference in handling keys; you might need to check whether you can then use keydown and keyup more successfully (they should indicate the keys pressed, and you would need to deduce the character from them in your program logic).

这篇关于特殊字符在OSX上的html keypress事件上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆