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

这个值比较诡异,它表示你按了键盘上的哪个按键。你按 acode 的值是 KeyA,你按左边的 Shiftcode 的值是 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>

显示结果如下:
在这里插入图片描述
当我们在键盘上输入键值时,会有相应的属性显示,也可以点击该链接实时尝试:

See the Pen keyboardEvent by suwu150 ( @suwu150) on CodePen.
Mouse​Event​

从上面我们了解到了键盘事件的监听,在这里我们继续学习鼠标事件的监听:
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)
按键键码按键键码按键键码按键键码
A65J74S83149
B66K75T84250
C67L76U85351
D68M77V86452
E69N78W87553
F70O79X88654
G71P80Y89755
H72Q81Z90856
I73R82048957
数字键盘上的键的键码值(keyCode)功能键键码值(keyCode)
按键键码按键键码按键键码按键键码
0968104F1112F7118
1979105F2113F8119
298*106F3114F9120
399+107F4115F10121
4100Enter108F5116F11122
5101-109F6117F12123
6102.110
7103/111
控制键键码值(keyCode)
按键键码按键键码按键键码按键键码
BackSpace8Esc27Right Arrow39-_189
Tab9Spacebar32Dw Arrow40.>190
Clear12Page Up33Insert45/?191
Enter13Page Down34Delete46`~192
Shift16End35Num Lock144[{219
Control17Home36;:186/|220
Alt18Left Arrow37=+187]}221
Cape Lock20Up Arrow38,<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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suwu150

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值