组合事件切换键

Event shift key in combination

我需要在 javascript 中撤消和重做。

ctrl + z = 撤消

ctrl + shift + z = 重做

在下面描述的代码中,撤消正常,但重做不起作用。我注意到如果它是 shift.key alon 那么它会起作用,如果与其他(shift.key + ctrl.key 或“z”)组合它不起作用。为什么..,或者我在代码的某个地方错了?

function isKeyPressedUndo(event) {
  var x = document.getElementById("demo");
  if (event.ctrlKey && event.key === 'z') {
    x.innerHTML = "The UNDO key was pressed!";
  } else {
    x.innerHTML = "The UNDO key was NOT pressed!";
  }
}

function isKeyPressedRedo(event) {
  var x = document.getElementById("demo");
  if (event.shiftKey && event.ctrlKey && event.key === 'z') {
    x.innerHTML += "The REDO key was pressed!";
  } else {
    x.innerHTML += "The REDO key was NOT pressed!";
  }
}
<input type="text" onkeydown="isKeyPressedUndo(event), isKeyPressedRedo(event)">

<p id="demo"></p>

调试 101:如果 if 语句失败,记录您正在测试的值

当按下 shift 键时 event.key 是大写字母 Z 不是小写字母 z.

function isKeyPressedUndo(event) {
  var x = document.getElementById("demo");
  if (event.ctrlKey && event.key === 'z') {
    x.innerHTML = "The UNDO key was pressed!";
  } else {
    x.innerHTML = "The UNDO key was NOT pressed!";
  }
}

function isKeyPressedRedo(event) {
  var x = document.getElementById("demo");
  console.log([event.shiftKey, event.ctrlKey, event.key]);
  if (event.shiftKey && event.ctrlKey && event.key === 'z') {
    x.innerHTML += "The REDO key was pressed!";
  } else {
    x.innerHTML += "The REDO key was NOT pressed!";
  }
}
<input type="text" onkeydown="isKeyPressedUndo(event), isKeyPressedRedo(event)">

<p id="demo"></p>

event.key 轮班是大写!

const x = document.getElementById("demo");
document.getElementById("text").addEventListener("keydown", function(event) {
  console.log("ctrl",event.ctrlKey,"shift",event.shiftKey,"key",event.key)
  if (event.ctrlKey) {
    if (event.key.toLowerCase() === 'z') {
      if (event.shiftKey) x.innerHTML = "The REDO key was pressed!";
      else x.innerHTML += "The UNDO key was pressed!";
    } else {
      if (event.key === 'y') x.innerHTML = "The REDO key was pressed!";
    }
  }
})
<input type="text" id="text" autocomplete="off">

<p id="demo"></p>

按下shift键时,按键变为Z(大写z)。

一般是not a good idea to use inline event handlers. Here's a somewhat simplified snippet, using event delegation.

document.addEventListener(`keydown`, handle);

function handle(event) {
  if (event.target.id === `keyTest`) {
    // toLowerCase for shift and/or caps lock
    const isZ = event.key.toLowerCase() === `z`;
    const [isUndo, isRedo] = [
      event.ctrlKey && !event.shiftKey && isZ,
      event.shiftKey && event.ctrlKey && isZ ];
    
    document.querySelector(`#demo`).innerHTML = isUndo ?
      `The UNDO key was pressed!` 
      : isRedo ? `The REDO key was pressed!` : `Regular input &hellip;`
  }
}
<input type="text" id="keyTest">

<p id="demo"></p>