交错按下和释放时 onkeyup 和 onkeydown 会产生干扰

问题描述 投票:0回答:1

顺序

  1. 按住 Shift 以外的键(例如 Alt),
  2. 按住Shift
  3. 释放自第 1 步以来按住的键,
  4. 释放Shift

导致“其他键”保持彩色,就像

= 'none'
线没有运行一样。


现在我正在另一个系统上尝试 Shift 不是唯一的,我可以使用 Ctrl 获得相同的效果(另一个键例如是 4 个箭头之一)。


这是为什么呢?这是不可避免的吗?

window.onkeydown = listenKeyDown;
window.onkeyup = listenKeyUp;

function listenKeyDown(e) {
  //console.log(e)
  if (e.altKey) {
    document.getElementById('alt').style.background = '#00ff00';
  }
  if (e.ctrlKey) {
    document.getElementById('ctrl').style.background = '#00ff00';
  }
  if (e.shiftKey) {
    document.getElementById('shift').style.background = '#00ff00';
  }
  let elem = document.getElementById(e.key);
  if (elem && !e.altKey && !e.ctrlKey && !e.shiftKey) {
    elem.style.background = '#00ff00';
  }
}

function listenKeyUp(e) {
  //console.log(e)
  if (e.altKey) {
    document.getElementById('alt').style.background = 'none';
  }
  if (e.ctrlKey) {
    document.getElementById('ctrl').style.background = 'none';
  }
  if (e.shiftKey) {
    document.getElementById('shift').style.background = 'none';
  }
  let elem = document.getElementById(e.key);
  if (elem && !e.altKey && !e.ctrlKey && !e.shiftKey) {
    document.getElementById(e.key).style.background = 'none';
  }
}
<div id="alt">Alt</div>
<div id="ctrl">Ctrl</div>
<div id="shift">Shift</div>
<div id="End">End</div>
<div id="Home">Start</div>
<div id="ArrowUp">Up</div>
<div id="ArrowLeft">Left</div>
<div id="ArrowDown">Down</div>
<div id="ArrowRight">Right</div>
<ol>
  <li>Hold down a key (listed above, but other than Shift),</li>
  <li>Hold Shift down</li>
  <li>Release the key of step 1</li>
  <li>Release Shift</li>
</ol>

javascript events onkeydown onkeyup
1个回答
0
投票

您可以使用

Set
来简化按下的按键。

const pressedKeys = new Set();

window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);

function handleKeyDown(e) {
  e.preventDefault();
  pressedKeys.add(e.key);
  update();
}

function handleKeyUp(e) {
  e.preventDefault();
  pressedKeys.delete(e.key);
  update();
}

function update(e) {
  for (let key of document.querySelectorAll('.key')) {
    key.classList.toggle('pressed', pressedKeys.has(key.dataset.key));
  }
}
.pressed {
  background: limegreen;
}
<div class="key" data-key="Alt">Alt</div>
<div class="key" data-key="Control">Ctrl</div>
<div class="key" data-key="Shift">Shift</div>
<div class="key" data-key="End">End</div>
<div class="key" data-key="Home">Start</div>
<div class="key" data-key="ArrowUp">Up</div>
<div class="key" data-key="ArrowLeft">Left</div>
<div class="key" data-key="ArrowDown">Down</div>
<div class="key" data-key="ArrowRight">Right</div>

© www.soinside.com 2019 - 2024. All rights reserved.