JavaScript如何实现监听键盘输入和鼠标监点击

实际应用中,我们会遇到监听按键输入和鼠标点击事件,在这里我们进行对鼠标和键盘事件的总结.

Keyboard​Event

KeyboardEvent 对象描述了键盘的交互方式。 每个事件都描述了一个按键(Each event describes a key);事件类型keydown, keypress 与 keyup 可以确定是哪种事件在活动。
KeyboardEvent 表示刚刚发生在按键上的事情。 当你需要处理文本输入的时候,使用 HTML5 input 事件代替。例如,用户使用手持系统如平板电脑输入时, 按键事件可能不会触发。

方法

本接口同样会继承对象父代的方法, UIEvent 和 Event。

  • KeyboardEvent.getModifierState()返回一个 Boolean,表示在事件创建时,修改键如Alt , Shift, Ctrl, Meta等是否按下。
  • KeyboardEvent.initKeyEvent()初始化一个 KeyboardEvent 对象。 现在的标准方式是使用 KeyboardEvent() 构造器。
  • KeyboardEvent.initKeyboardEvent() 初始化一个 KeyboardEvent 对象。 现在的标准方式是使用 KeyboardEvent() 构造器。

介绍下我们常用的一些属性:

  • KeyboardEvent.key
  • KeyboardEvent.code
  • KeyboardEvent.ctrlKey
  • KeyboardEvent.shiftKey
  • KeyboardEvent.altKey
  • KeyboardEvent.metaKey

KeyboardEvent.ctrlKey | shiftKey | altKey | metaKey 比较简单,表示当你按下键盘的时候,Ctrl | Shift | Alt | meta 按键是否已经被按下。如果已经被按下这些值就是 true,通常我们要运用组合键的判断会用到(譬如:Alt + a)。大家看到 meta 会疑惑这个是哪个键?在 Mac 平台上指的是 command 键(⌘),而在 Windows 平台指的是 windows 键(⊞)。但是不是所有 Windows 电脑键盘都有 ⊞ 这个键的。接下来我们介绍下最重要的两个属性 key 和 code。

KeyboardEvent.key

如果你按下的按钮所代表的是一个可打印的字符(printed representation),那么这个 key 的值就是这个字符(譬如:a、Enter、Shift、CapsLock、Backspace)。。

KeyboardEvent.code

这个值比较诡异,它表示你按了键盘上的哪个按键。你按 a,code 的值是 KeyA,你按左边的 Shift,code 的值是 ShiftLeft。什么意思呢?就是他表示你按的按键在键盘的哪个位置。这里就有趣了,因为不同语言的键盘同一个键代表的字符可能不同,但是位置是相同的。打个比方:KeyQ 代表的是我们普通键盘q按键。但是呢 Dvorak 键盘q这个位置的按钮代表的不是 q,而是'。所以如果你按同一个按钮,key 的值可能不同,code 的值会相同。

KeyboardEvent.keyCode 只读

返回一个表示系统和实现相关的数字代码的 Number, 用于标识按键的未修改值。
了解了上面属性,我们就可以进行使用代码的方式实时获取输入的键值

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>键盘事件监听</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }

  #container {
   display: flex;
   flex-direction: row;
   justify-content: center;
   align-items: center;
   padding-top: 20px;
  }

  table,
  table tr th,
  table tr td {
   border: 1px solid #000;
  }

  table {
   min-height: 25px;
   line-height: 25px;
   text-align: center;
   border-collapse: collapse;
   padding: 2px;
  }

  th {
   width: 150px;
  }
 </style>
 <script type="text/javascript" language=JavaScript>
  window.onload = function () {
   const key = document.getElementById('key');
   const keyCode = document.getElementById('keyCode');
   const code = document.getElementById('code');
   const ctrlKey = document.getElementById('ctrlKey');
   const metaKey = document.getElementById('metaKey');
   const shiftKey = document.getElementById('shiftKey');
   const altKey = document.getElementById('altKey');
   const combineKey = document.getElementById('combineKey');


   document.onkeydown = function(event) {
   var e = event || window.event || arguments.callee.caller.arguments[0];
   e.preventDefault(); //阻止默认事件
   // 设置获取的值
   key.innerHTML = e.key;
   keyCode.innerHTML = e.keyCode;
   code.innerHTML = e.code;
   ctrlKey.innerHTML = e.ctrlKey;
   metaKey.innerHTML = e.metaKey;
   shiftKey.innerHTML = e.shiftKey;
   altKey.innerHTML = e.altKey;

   if (e.altKey || e.shiftKey || e.metaKey || e.ctrlKey) {
    let result = '';
    if (e.altKey) {
    result = 'Alt';
    } else if (e.shiftKey) {
    result = 'Shift';
    } else if (e.metaKey) {
    result = 'Meta';
    } else if (e.ctrlKey) {
    result = 'Control';
    }
    combineKey.innerHTML = result !== e.key ? `${result} + ${e.key}` : `${result}`;
   } else {
    combineKey.innerHTML = '-';
   }
   };
  }
 </script>
</head>
<body>
<div id="container">
 <table border="0px">
  <tr>
   <th>key</th>
   <th>keyCode</th>
   <th>code</th>
   <th>ctrlKey</th>
   <th>metaKey</th>
   <th>shiftKey</th>
   <th>altKey</th>
   <th>组合健</th>
  </tr>
  <tr>
   <td id="key">-</td>
   <td id="keyCode">-</td>
   <td id="code">-</td>
   <td id="ctrlKey">-</td>
   <td id="metaKey">-</td>
   <td id="shiftKey">-</td>
   <td id="altKey">-</td>
   <td id="combineKey">-</td>
  </tr>
 </table>
 <hr />
</div>
</body>
</html>

显示结果如下:

MouseEvent 接口指用户与指针设备( 如鼠标 )交互时发生的事件。使用此接口的常见事件包括:click,dblclick,mouseup,mousedown。

介绍下我们常用的一些属性:

  • MouseEvent.altKey 只读,当鼠标事件触发的时,如果alt 键被按下,返回true;
  • MouseEvent.button 只读,当鼠标事件触发的时,如果鼠标按钮被按下(如果有的话),将会返回一个数值。这些数值代表的意义分别是,button=0(鼠标左键),button=2(鼠标右键),button=1(鼠标中间键)
  • MouseEvent.buttons 只读,当鼠标事件触发的时,如果多个鼠标按钮被按下(如果有的话),将会返回一个或者多个代表鼠标按钮的数字。这些数值代表的意义分别是,buttons=1(鼠标左键),buttons=2(鼠标右键),buttons=3(同时按下左健和右键),buttons=4(鼠标中间键),buttons=5(同时按下左健和中间键),buttons=6(同时按下中间健和右键),buttons=7(同时按下左健、右键和中间键).
  • MouseEvent.clientX 只读,鼠标指针在点击元素(DOM)中的X坐标。
  • MouseEvent.clientY 只读,鼠标指针在点击元素(DOM)中的Y坐标。
  • MouseEvent.ctrlKey 只读,当鼠标事件触发时,如果 control 键被按下,则返回 true;
  • MouseEvent.metaKey 只读,当鼠标事件触发时,如果 meta键被按下,则返回 true;
  • MouseEvent.shiftKey 只读当鼠标事件触发时,如果 shift 键被按下,则返回 true;
  • MouseEvent.which 只读,当鼠标事件触发时,表示被按下的按钮

同样的,我们使用代码进行获取鼠标点击时触发的值

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>键盘事件监听</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }

  #container {
   display: flex;
   flex-direction: row;
   justify-content: center;
   align-items: center;
   padding-top: 20px;
  }

  table,
  table tr th,
  table tr td {
   border: 1px solid #000;
  }

  table {
   min-height: 25px;
   line-height: 25px;
   text-align: center;
   border-collapse: collapse;
   padding: 2px;
  }

  th {
   width: 130px;
  }
 </style>
 <script type="text/javascript" language=JavaScript>
  function doNothing(){
  window.event.returnValue=false;
  return false;
  }

  window.onload = function () {
   const button = document.getElementById('button');
   const buttons = document.getElementById('buttons');
   const clientX = document.getElementById('clientX');
   const clientY = document.getElementById('clientY');
   const ctrlKey = document.getElementById('ctrlKey');
   const metaKey = document.getElementById('metaKey');
   const shiftKey = document.getElementById('shiftKey');
   const altKey = document.getElementById('altKey');
   const which = document.getElementById('which');
   const combineKey = document.getElementById('combineKey');


   document.onmousedown = function(event) {
   var e = event || window.event || arguments.callee.caller.arguments[0];
   e.preventDefault(); //阻止默认事件
   // 设置获取的值
   button.innerHTML = e.button;
   buttons.innerHTML = e.buttons;
   clientX.innerHTML = e.clientX;
   clientY.innerHTML = e.clientY;
   ctrlKey.innerHTML = e.ctrlKey;
   metaKey.innerHTML = e.metaKey;
   shiftKey.innerHTML = e.shiftKey;
   altKey.innerHTML = e.altKey;
   which.innerHTML = e.which;

   function getButton(value) {
    let buttonname = '';
    if (value === 0) buttonname = '鼠标左键';
    if (value === 1) buttonname = '鼠标中间键';
    if (value === 2) buttonname = '鼠标右键';
    return buttonname;
   }

   if (e.altKey || e.shiftKey || e.metaKey || e.ctrlKey) {
    let result = '';
    if (e.altKey) {
    result = 'Alt';
    } else if (e.shiftKey) {
    result = 'Shift';
    } else if (e.metaKey) {
    result = 'Meta';
    } else if (e.ctrlKey) {
    result = 'Control';
    }
    combineKey.innerHTML = `${result} + ${getButton(e.button)}`;
   } else {
    combineKey.innerHTML = getButton(e.button);
   }
   };
  }
 </script>
</head>
<body oncontextmenu="doNothing()">
<div id="container">
 <table border="0px">
  <tr>
   <th>button</th>
   <th>buttons</th>
   <th>clientX</th>
   <th>clientY</th>
   <th>ctrlKey</th>
   <th>metaKey</th>
   <th>shiftKey</th>
   <th>altKey</th>
   <th>which</th>
   <th>组合健</th>
  </tr>
  <tr>
   <td id="button">-</td>
   <td id="buttons">-</td>
   <td id="clientX">-</td>
   <td id="clientY">-</td>
   <td id="ctrlKey">-</td>
   <td id="metaKey">-</td>
   <td id="shiftKey">-</td>
   <td id="altKey">-</td>
   <td id="which">-</td>
   <td id="combineKey">-</td>
  </tr>
 </table>
 <hr />
</div>
</body>
</html>

效果如下:

可参见以下链接进行操作:

See the Pen MouseEvent by suwu150 (@suwu150) on CodePen.

常见键值

字母和数字键的键码值(keyCode)
按键 键码 按键 键码 按键 键码 按键 键码
A 65 J 74 S 83 1 49
B 66 K 75 T 84 2 50
C 67 L 76 U 85 3 51
D 68 M 77 V 86 4 52
E 69 N 78 W 87 5 53
F 70 O 79 X 88 6 54
G 71 P 80 Y 89 7 55
H 72 Q 81 Z 90 8 56
I 73 R 82 0 48 9 57
数字键盘上的键的键码值(keyCode) 功能键键码值(keyCode)
按键 键码 按键 键码 按键 键码 按键 键码
0 96 8 104 F1 112 F7 118
1 97 9 105 F2 113 F8 119
2 98 * 106 F3 114 F9 120
3 99 + 107 F4 115 F10 121
4 100 Enter 108 F5 116 F11 122
5 101 - 109 F6 117 F12 123
6 102 . 110
7 103 / 111
控制键键码值(keyCode)
按键 键码 按键 键码 按键 键码 按键 键码
BackSpace 8 Esc 27 Right Arrow 39 -_ 189
Tab 9 Spacebar 32 Dw Arrow 40 .> 190
Clear 12 Page Up 33 Insert 45 /? 191
Enter 13 Page Down 34 Delete 46 `~ 192
Shift 16 End 35 Num Lock 144 [{ 219
Control 17 Home 36 ;: 186 /| 220
Alt 18 Left Arrow 37 =+ 187 ]} 221
Cape Lock 20 Up Arrow 38 ,< 188 '" 222
多媒体键码值(keyCode)
按键 键码 按键 键码 按键 键码 按键 键码
音量加 175
音量减 174
停止 179
静音 173
浏览器 172
邮件 180
搜索 170
收藏 171

参考链接:

1.https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent
2.https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/ctrlKey

到此这篇关于JavaScript如何实现监听键盘输入和鼠标监点击的文章就介绍到这了,更多相关JavaScript键盘鼠标监听功能内容请搜索来客网以前的文章或继续浏览下面的相关文章希望大家以后多多支持来客网!