如何在按下 ESC 键时执行 JS 代码块?

How to execute a JS code block on pressing ESC key?

我想在用户按下 ESC 键时执行 JS 代码。请帮帮我,我该怎么做?我当前的代码不工作。我不知道我哪里做错了?我只是一个初学者所以请帮助我..

function hideModalKeyPress(e)
{
 if(e.keyCode == 27)
 {
  document.getElementsByClassName('modalOverlay')[0].style.visibility = "hidden";
 }
}
.modalOverlay
{
  width: 200px;
  height: 200px;
  opacity: 0.8;
  background-color: black;
  visibility: visible;
}
<div class="modalOverlay" onkeydown="hideModalKeyPress(e);">Press ESC to hide me.</div>

/*
 * I want to set the div's visibility to hidden
 * when user presses ESC key
*/

您可以使用 jQuery 并执行以下操作:

$(document).keyup(function(e) {
  if (e.keyCode == 27) {
      $(".modalOverlay").css('visibility', 'hidden');
  }   
});

JSFiddle

或纯 JavaScript:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        document.getElementById("modal").style.visibility = "hidden";
    }
};

JSFiddle

这对我有用:

document.addEventListener("keydown", hideModalKeyPress, false);
function hideModalKeyPress(e) {
    if(e.keyCode === 27)
    {
        document.getElementsByClassName('modalOverlay')[0].style.visibility = "hidden";
    }
}

这是有效的 jsfiddle: https://jsfiddle.net/7jrfrz26/