我想让我的模态框在按下ESC键时关闭(删除设置为
display: block
的类)。以下是我尝试过的代码(不起作用并且破坏了我的其余代码):if (modal.classList.contains('modal-visible')) {
document.addEventListener('keypress', function(e) {
let keyCode = e.keyCode;
if (keyCode === '27') {
modal.classList.remove('modal-visible');
}
}
以下是我JS文件中用于模态框的其他代码:
const modal = document.getElementById('myModal');
const closeIcon = document.querySelector('.close');
// When called, adds class that sets modal to display: block when player reaches water
function bringUpModal() {
modal.classList.add('modal-visible');
}
// Closes modal (adding class that sets it back to display: none) upon user's clicking its close icon
closeIcon.addEventListener('click', function() {
modal.classList.remove('modal-visible');
});
// Opens modal when player reaches water
Player.prototype.update = function(dt) {
if (this.y === 25) {
bringUpModal();
this.y = 400;
}
};
如果需要的话,这是我的模态框CSS:
.modal {
display: none;
width: 33%;
height: 30%;
margin: 0 auto;
background-color: #f1f0f0;
border: 1px solid #c5c4c4;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Added by function bringUpModal() */
.modal-visible {
display: block;
}
.modal-content {
margin: 0 auto;
padding: 30px;
width: 80%;
display: flex;
flex-direction: column;
justify-content: center;
}
modal-visible
类都会被移除。 此外,如果if检查为false,则根本不会创建监听器! 最后,请检查您的第一个代码片段中的括号和方括号是否匹配。它们看起来不匹配,这可能是导致代码出错的原因 :) - Andrey