如何实现点击页面任意位置关闭Modal,无需仅点击指定按钮
具体修改步骤
你只需要在现有代码基础上新增3段逻辑即可,不需要改动原有功能的代码:
- 给原按钮的点击事件添加事件冒泡阻止,避免点击按钮时触发后续的全局点击关闭逻辑
- 给Modal(信息弹窗)本身添加事件冒泡阻止,避免点击弹窗内容时触发关闭
- 给全局页面添加点击事件,判断弹窗处于打开状态时自动执行关闭操作
修改后的完整代码如下:
const bf = document.querySelector('#botsquad-frame'); let el = document.createElement('div'); el.setAttribute('id', 'mijnKnopje'); const inhoud = ` <div class="info-content"> <p1>INFORMATIE: <br> By participating within this chat, you accept that some of the answers you give will be displayed on one of the screens within the installation. <br><br> HOW TO:<br> Go in conversation with Nostos and Algia, ask them questions and discuss multiple topics. </p1> </div> <div class="info-section"> <a role="button" class="knopje info-button" style="background-color:mediumpurple"> <div class="info-label">!</div> </a> </div> `; el.innerHTML = inhoud; bf.appendChild( el ); const mijnKnopje = document.querySelector('.knopje'); const mijnInfo = document.querySelector('.info-content'); mijnKnopje.addEventListener('click', (e) => { // 新增:阻止事件冒泡到全局 e.stopPropagation(); mijnKnopje.classList.toggle( 'active' ); mijnInfo.classList.toggle( 'active' ); let inputField = document.querySelector('.chat-input'); if ( mijnInfo.classList.contains( 'active' ) ) { inputField.style.display = 'none'; } else { inputField.style.display = 'revert'; } } ); // 新增:点击弹窗本身不触发关闭 mijnInfo.addEventListener('click', (e) => { e.stopPropagation(); }); // 新增:全局点击关闭弹窗逻辑 document.addEventListener('click', () => { if (mijnInfo.classList.contains('active')) { mijnKnopje.classList.remove('active'); mijnInfo.classList.remove('active'); const inputField = document.querySelector('.chat-input'); inputField.style.display = 'revert'; } });
逻辑说明
事件冒泡是浏览器默认的事件传递机制,点击子元素的事件会一层层传递给父元素直到全局,我们加的e.stopPropagation()就是阻止这个传递,避免点击按钮/弹窗的时候触发全局的点击事件。全局点击事件的逻辑只在弹窗处于激活状态的时候才执行,不影响页面其他正常交互。
内容的提问来源于stack exchange,提问作者sachava
相关产品推荐
相关产品推荐

