javascript - 跨浏览器跨操作系统获取 keyCode/字符按下 onkeydown 事件的方法

标签 javascript dom

例如,如果我有这个:

<input type='text' onkeydown='doSomething()' />

<script>
  function doSomething() {
    // ?
  }
</script>

我需要以跨浏览器/操作系统的方式按下 keyCode/character .. 怎么做?我在 6 年前尝试过这个,我记得那个时候,这并不容易,有时我必须通过事件或其他东西才能让它在歌剧或 IE cmiiw 上工作

最佳答案

你已经接近了,但你的代码的问题是你正在执行 doSomething()回应keyDown事件...让我们仔细看看——你正在执行 doSomething没有传递任何参数。即使您确实传递了参数,您也没有命名/接受参数。

对您的代码进行一些快速调整,一切就绪:

// Notice an `event` argument, containing the important data
function doSomething(event) {
  console.log('****** doSomething');
  console.log('event.keyCode: ', event.keyCode);
  console.log('event.which: ', event.which);
  console.log('event.key: ', event.key);
  console.log('event.code: ', event.code);
}
<!-- Notice: We pass the key `event` object into doSomething -->
<input type='text' onkeydown='doSomething(event)' placeholder="Type here..." />


如何确定按下了什么键

我对此也感到困惑,但让我们回顾一下这些选项。为 1995 年的浏览器差异做好准备!

首先,请记住,虽然最终目标可能是确定按下了哪个键,但不同的方法需要不同的步骤才能实现。事件可以是“系统和实现相关的数字代码”、Unicode 字符值、Ascii 值或实际键名(“ArrowUp”)。
event.key ( TL;DR:尝试使用这个 )

根据MDN KeyboardEvent.key Documentation , event.key如果您正在寻找不被弃用的“面向 future ”的方式,这是推荐的方式。文档正在大量修改中,因此 MDN 上的细节很少。

看着caniuse.com support table对于 event.key ,在 IE11 以下或 Safari 上根本不支持(截至 2017 年 1 月)。这可能已经是一个交易破坏者,所以让我们继续寻找。
event.keyCode
我一直用event.keyCode , 其中 MDN says is now deprecated并附带此警告:

You should avoid using this if possible; it's been deprecated for some time. Instead, you should use KeyboardEvent.code, if it's implemented. Unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers. Google Chrome and Safari have implemented KeyboardEvent.keyIdentifier, which was defined in a draft specification but not the final spec.



好吧,很公平——浏览器之间有足够的差异,keydown 之间有细微的差异。和 keypress事件( not the same thing! )使其不再值得使用。 RIP keyCode ,这是真的!
event.which
来自 MDN docs :

The numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. Please see KeyboardEvent.charCode** and KeyboardEvent.keyCode for more details.



另一个正在弃用的——“这个特性已经从 Web 标准中删除。虽然一些浏览器可能仍然支持它,但它正在被删除。”

好吧,好吧keyCode我们已经知道它也被弃用了,那么 charCode 是什么?关于?
event.charCode
这将返回 keypress 的 Unicode 字符代码事件...和we get another warning from MDN :

Do not use this property anymore, it is deprecated. Use KeyboardEvent.key instead.



开始在这里追逐我们自己的尾部,KeyboardEvent.key是面向 future 的方法,但尚未得到充分支持...它还返回 0一直为keydown事件,你必须听keypress事件才有值(value)。
event.code
最后一个选项似乎很有希望... event.code docs from MDN :

represents a physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value which isn't altered by keyboard layout or the state of the modifier keys.



这很方便,因为我们得到了像 ShiftRight 这样的东西。与 ShiftLeft 相比,对于游戏开发和非常具体的交互很有用。所有代码选项的文档底部都有一个很棒的图表。

收获:not very good support yet . IE、iOS Safari、Android 或 Opera 上没有任何内容。

那么......我应该使用什么?

TBH 我认为没有一刀切的解决方案。目前的情况似乎需要某种程度的 polyfill,或者至少支持旧的 event.keyCodeevent.which属性作为 where event.key 的后备和 event.code不能使用。

对于生产项目,我们只需要考虑浏览器和设备支持要求,然后从那里开始。

Shift/Ctrl/Command/Windows/等

有一些额外的属性可以检查您是否关心与原始键组合按下的其他键:
  • event.altKey
  • event.ctrlKey
  • event.metaKey
  • event.shiftKey

  • 方便的工具:keycode.info
    http://keycode.info/ 是一个非常有用的工具,可以快速找出您需要围绕哪些 keyCode 编写逻辑。 (由 v.cool Wes Bos 创建)

    关于javascript - 跨浏览器跨操作系统获取 keyCode/字符按下 onkeydown 事件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15108670/

    相关文章:

    javascript - 当使用 element.style = <some CSSStyleDeclaration> 使元素消失

    java - 如何解析 XML 标签中的换行符?

    javascript - 如何在传递给另一个组件的函数中获取 useState 变量的值

    javascript - 如何一次为每个用户添加一个子级到另一个子级 Firebase 下?

    javascript - 如何删除具有云功能的 Node ?

    javascript - Uncaught TypeError : $. post 不是一个函数

    javascript - ExpressionChangedAfterItHasBeenCheckedError : Expression has changed after it was checked. 先前值 : 'ngIf: false' . 当前值: 'ngIf: true'

    java - 对元素的 DOM 属性序列进行排序

    javascript - 创建一个包含 Doctype 的新 HTML 文档

    html - 使用 JS 函数生成 Dom 的库