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

时间:2015-06-03 18:17:23

标签: javascript keycode event-listener

我想在用户按 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
*/

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

这对我有用:

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

这是工作的jsfiddle: https://jsfiddle.net/7jrfrz26/