2 回答

TA貢獻1719條經驗 獲得超6個贊
當您在模態窗口外部單擊時,事件傳播數組中不應包含模態窗口
換句話說,利用 event.path 屬性
工作示例(基于提供的小提琴)
window.addEventListener('click', function(e) {
const allModals = document.querySelectorAll('.project-card');
if (!e.path.some(x => x.className && x.className.includes('project-card'))) {
allModals.forEach(x => x.style.display = 'none');
}
}, true)
工作小提琴示例: https: //jsfiddle.net/7pzs1042/

TA貢獻1934條經驗 獲得超2個贊
window.addEventListener('click', function(e) {
? const allModals = document.querySelectorAll('.project-card');
??
//e.path is deprecated
// use instead e.composedPath() like this:?
? let paths = e.composedPath()
if (!paths.some(x => x.className && x.className.includes('project-card'))) {
? ? allModals.forEach(x => x.style.display = 'none');
? }
}, true)
添加回答
舉報