3

在 Javascript键盘事件中,为按下的键提供了一个代码,但是,它不是 ASCII 或 UTF-8 字符代码,而是键盘键的代码。有时 keyCode 恰好与 ASCII/UTF-8 代码匹配,有时则不匹配。

有没有办法,给定一个 Javascript 键码(通过e.keyCode或访问e.which)来获取相应的 ASCII 或 UTF-8 字符码?

这是一个有效的 JSFiddle来演示我的意思,或者运行下面的代码片段。

document.addEventListener("keyup", function(e) {

  document.querySelector(".key").innerHTML = e.key;
  document.querySelector(".keyCode").innerHTML = e.keyCode;
  document.querySelector(".UTF").innerHTML = String.fromCharCode(event.keyCode);

});
code {
  background-color: #e2aec8ab;
  border: solid 1px gray;
  border-radius: 3px;
  padding: 0 .5em;
  min-height: 1em;
  min-width: .2em;
  margin: 0 .1em;
}

.output {
  margin: 2em;
  border: solid 1px lightgray;
  border-radius: 3px;
  background-color: rgba(200, 250, 230, .3);
  padding: 1em;
}
Type here. Try some alpha letters as well as special keys like <code>`</code>
<code>-</code>
<code>=</code>
<code>[</code>
<code>]</code>
<code>[ENTER]</code>
<code>;</code>
<code>'</code>


<div class="output">
  You typed <code class="key"></code> which is Javascript <b></b>keyCode</b> <code class="keyCode"></code>, in UTF that would be <code class="UTF"></code>
</div>

两个例子:

  1. 2在键盘上键入
  2. 捕捉事件。event.keyCode是 50。
  3. UTF 字符 50 是2数字二

但:

  1. [在键盘上键入
  2. 捕捉事件。event.keyCode是 219。
  3. UTF 字符 219 是Û带有 CIRCUMFLEX 的拉丁大写字母 U
  4. 我希望事件包含的字符代码91对应于LEFT SQUARE BRACKET

如何将 Javascript 键码(例如219)转换为 UTF-8 字符码(例如91)?

4

1 回答 1

4

我只想说,这个问题变成了一次有趣的学习冒险。但....

您正在使用已弃用的 API。

事实证明,KeyboardEvent.keyCode已经被弃用了一段时间。因为它使用 ASCII 的十进制版本。要使用的正确代码实际上是event.Code. 但这不是你所追求的。

要获取 ascii 编号,您可以使用event.key.charCodeAt()This does have some 缺陷,因为它会S在您按下 shift 时报告。但是你可以用event.location它来判断这个键是否是一个特殊的控制键。零是标准键,1-3 是特殊位置(我认为)。

document.addEventListener("keyup", function(e) {

  document.querySelector(".key").innerHTML = e.key;
  document.querySelector(".keyCode").innerHTML = e.code;
  document.querySelector(".ascii").innerHTML = e.key.charCodeAt()
  document.querySelector(".UTF").innerHTML = String.fromCharCode(event.key.charCodeAt());

});
code {
  background-color: #e2aec8ab;
  ;
  border: solid 1px gray;
  border-radius: 3px;
  padding: 0 .5em;
  min-height: 1em;
  min-width: .2em;
  margin: 0 .1em;
}

.output {
  margin: 2em;
  border: solid 1px lightgray;
  border-radius: 3px;
  background-color: rgba(200, 250, 230, .3);
  padding: 1em;
}
Type here. Try some alpha letters as well as special keys like <code>`</code>
<code>-</code>
<code>=</code>
<code>[</code>
<code>]</code>
<code>[ENTER]</code>
<code>;</code>
<code>'</code>


<div class="output">
  You typed <code class="key"></code> which is Javascript <b>keyCode</b> <code class="keyCode"></code>, in ASCII that would be <code class="ascii"> </code> which is <code class="UTF"></code>
</div>

于 2020-11-19T06:44:20.700 回答