javascript – 检测可打印的键

前端之家收集整理的这篇文章主要介绍了javascript – 检测可打印的键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要检测刚被按下的键是一个可打印的键,如字符,可能有重音,数字,空格,标点符号等,还是不可打印的键,如ENTER,TAB或DELETE.

有没有可靠的方式来做这个Javascript,除了列出所有不可打印的键,希望不要忘记一些?

解决方法

我昨天回答了一个 similar question.请注意,您必须使用按键事件与任何字符相关; keydown不会做.

我会认为Enter是可打印的,顺便说一下,这个功能认为它是.如果您不同意,您可以修改它,以将该事件的哪个或keyCode属性设置为13来过滤掉按键.

  1. function isCharacterKeyPress(evt) {
  2. if (typeof evt.which == "undefined") {
  3. // This is IE,which only fires keypress events for printable keys
  4. return true;
  5. } else if (typeof evt.which == "number" && evt.which > 0) {
  6. // In other browsers except old versions of WebKit,evt.which is
  7. // only greater than zero if the keypress is a printable key.
  8. // We need to filter out backspace and ctrl/alt/Meta key combinations
  9. return !evt.ctrlKey && !evt.MetaKey && !evt.altKey && evt.which != 8;
  10. }
  11. return false;
  12. }
  13.  
  14. var input = document.getElementById("your_input_id");
  15. input.onkeypress = function(evt) {
  16. evt = evt || window.event;
  17.  
  18. if (isCharacterKeyPress(evt)) {
  19. // Do your stuff here
  20. alert("Character!");
  21. }
  22. });

猜你在找的JavaScript相关文章