首页 > 解决方案 > 不允许使用 ESC 键关闭模态窗口

问题描述

我在使用 ESC 键关闭模式窗口时遇到问题。我有这个脚本:

var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a 
caption
var imgs = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");

for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener('click', e => {
  modal.style.display = "block";
  modalImg.src = e.target.src;
  captionText.innerHTML = e.target.alt;
});
}

 // Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
 modal.style.display = "none";
}

我希望不仅可以通过单击 X 按钮,还可以通过 ESC 键来关闭它。我不太擅长 javascript,所以如果你告诉我应该在代码中包含什么,我会非常高兴。

此致!

标签: javascriptjquery

解决方案


也许您可以在整个文档上调用onkeyup,检查 ESC 键,然后将模式显示设置为无。

document.onkeyup = function (e) {
    e = e || window.event;

    // 27 is the ESC key
    if(e.keyCode === 27) modal.style.display = "none";
};

推荐阅读