我想在用户按 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
*/
答案 0 :(得分:0)
您可以使用jQuery并执行以下操作:
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$(".modalOverlay").css('visibility', 'hidden');
}
});
或者在纯JavaScript中:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
document.getElementById("modal").style.visibility = "hidden";
}
};
答案 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/