如何通过按 esc 关闭模态框

问题描述 投票:0回答:1

我是 Javascript 新手,除了单击跨度之外,我还想通过按

esc
键来关闭此模式。怎么写呢?

var modal = document.getElementById('myModal');
                        var img = document.getElementById('myImg');
                        var img2 = document.getElementById('myImg2');
                        var img3 = document.getElementById('myImg3');
                        var img4 = document.getElementById('myImg4');
                        var modalImg1 = document.getElementById("img01");
                        var captionText = document.getElementById("caption");

                            img.onclick = function()
                                {
                                    modal.style.display = "block";
                                    modalImg1.src = this.src;
                                    captionText.innerHTML = this.alt;
                                }
                            img2.onclick = function()
                                {
                                    modal.style.display = "block";
                                    modalImg1.src = this.src;
                                    captionText.innerHTML = this.alt;
                                }   
                            img3.onclick = function()
                                {
                                    modal.style.display = "block";
                                    modalImg1.src = this.src;
                                    captionText.innerHTML = this.alt;
                                }   
                            img4.onclick = function()
                                {
                                    modal.style.display = "block";
                                    modalImg1.src = this.src;
                                    captionText.innerHTML = this.alt;
                                }   

                            var span = document.getElementsByClassName("close")[0];

                            span.onclick = function() 
                            { 
                                modal.style.display = "none"; 
                            }

我正在考虑在该跨度之后添加:

window.onkeypress = function (event) 
                            {
                                if (event.keyCode == 27 && modal.style.display='block') 
                                    {
                                        modal.style.display='none';
                                    }
                            }

但老实说不知道哪里出了问题

感谢您的帮助。

javascript html modal-dialog
1个回答
0
投票

尝试使用

onkeyup
而不是
onkeypress

window.onkeyup = function (event) {
    if (event.keyCode == '27' && modal.style.display=='block') {
        modal.style.display='none';
    }
}

为什么?

使用

onkeypress
,您将获得针对不同浏览器的不同密钥代码。 检查以下线程: jQuery 的转义键的键码是哪个 和: 如何用纯JS或jQuery检测转义键按下?

© www.soinside.com 2019 - 2024. All rights reserved.