我是Javascript的新手,除了单击span之外,我还想通过按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';
}
}
但老实说不知道那里出了什么问题
感谢您的任何帮助。
尝试使用 onkeyup
而不是 onkeypress
:
window.onkeyup = function (event) {
if (event.keyCode == '27' && modal.style.display=='block') {
modal.style.display='none';
}
}
为什么?
使用onkeypress
,您将获得不同浏览器的不同键码。在 SO 上检查这些线程:使用jQuery的转义键的哪个键码和:如何检测纯JS或jQuery的转义键按下?