當用戶按下 Esc 鍵時,我試圖隱藏“模態”框。
- 因此,我首先檢查框包含類的位置 - “隱藏”,這在技術上將框隱藏在 UI 中。
- 然后,如果它沒有隱藏(該框不包含類 - '隱藏')并出現在螢屏上,該函式將等待 Esc 鍵使該框消失。
顯示和隱藏框部件作業正常,但document.addEventListener部件不起作用。
const btnopenModal = document.querySelectorAll('.show-modal');
const btnCloseModal = document.querySelector('.close');
const overlay = document.querySelector('.overlay');
const modal =document.querySelector('.modal');
const showModal = function() {
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
const hideModal = function() {
modal.classList.add('hidden');
overlay.classList.add('hidden');
}
for(let i = 0; i < btnopenModal.length; i )
btnopenModal[i].addEventListener('click', showModal);
btnCloseModal.addEventListener('click', hideModal);
overlay.addEventListener('click', hideModal);
if(!overlay.classList.contains('hidden')) {
document.addEventListener('keypress', function(e) {
console.log(e.key);
if(e.key === 'Escape') {
hideModal();
}
})
};
有什么其他方法可以解決這個問題嗎?
uj5u.com熱心網友回復:
我認為您的 if 陳述句會在網頁首次運行時進行評估,我的猜測是 if 陳述句的計算結果為 false,因為它最初可能確實包含“隱藏”類。我不明白為什么你把它放在 if 陳述句中的關鍵處理程式,如果為了安全你應該把它放在你的函式中,如下所示:
document.addEventListener('keypress', function(e) {
if(!overlay.classList.contains('hidden')) {
console.log(e.key);
if(e.key === 'Escape') {
hideModal();
}
};
})
uj5u.com熱心網友回復:
移動 if 條件進入回呼。您想始終添加keypress偵聽器,hideModal()如果不執行就不要執行!overlay.classList.contains('hidden')
const btnopenModal = document.querySelectorAll('.show-modal');
const btnCloseModal = document.querySelector('.close');
const overlay = document.querySelector('.overlay');
const modal =document.querySelector('.modal');
const showModal = function() {
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
const hideModal = function() {
modal.classList.add('hidden');
overlay.classList.add('hidden');
}
for(let i = 0; i < btnopenModal.length; i )
btnopenModal[i].addEventListener('click', showModal);
btnCloseModal.addEventListener('click', hideModal);
overlay.addEventListener('click', hideModal);
document.addEventListener('keypress', function(e) {
console.log(e.key);
if(e.key === 'Escape' && !overlay.classList.contains('hidden')) {
hideModal();
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404548.html
標籤:
