我有使用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并不擅长,所以如果你告诉我应该在代码中加入什么,我会非常高兴。
祝你好运!
答案 0 :(得分:0)
也许您可以在整个文档上调用onkeyup,检查ESC键,然后将模态显示设置为无。
document.onkeyup = function (e) {
e = e || window.event;
// 27 is the ESC key
if(e.keyCode === 27) modal.style.display = "none";
};