javascript - 不允许使用 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,所以如果你告诉我应该在代码中包含什么,我会非常高兴。
此致!
解决方案
也许您可以在整个文档上调用onkeyup,检查 ESC 键,然后将模式显示设置为无。
document.onkeyup = function (e) {
e = e || window.event;
// 27 is the ESC key
if(e.keyCode === 27) modal.style.display = "none";
};
推荐阅读
- python - 如何在 Django DetailView 中显示对象列表
- mysql - 如何进行 LEFT JOIN,但行与 MySQL 中的关系分开?
- c++ - C++。返回带有指向堆的原始指针的本地对象。为什么它不崩溃?
- whitespace - pyparsing:匹配同一行上的单词
- python-3.x - Python:如何处理 https 连接被拒绝错误并将日志写入服务器
- vaadin - Vaadin 14 - 网格列标题格式
- php - 'service' 不是内部或外部命令、可运行程序或批处理文件
- r - 有没有办法修复 tableOutPut 或 dataTableOutput 的高度?
- javascript - Axios 没有调用 localhost API
- node.js - SQLTools vscode扩展SQLite依赖问题