JavaScript点击外部关闭两个提示div仅单个生效问题排查
问题根源
document.onclick是DOM元素的单值事件属性,重复赋值时后写入的处理函数会直接覆盖之前绑定的逻辑。你的代码中先后两次给document.onclick绑定不同的处理函数,最终只有后写入的逻辑生效,两个提示的关闭判断没有同时执行,因此会出现单个提示无法正常关闭的现象。
修复代码
把两个提示的关闭判断逻辑合并到同一个document点击事件处理函数中即可,修改后的完整代码如下:
function hideAlertInc() { document.getElementById("alert-inc").style.display = "none"; } function hideAlertCo() { document.getElementById("alert-co").style.display = "none"; } document.onclick = function (e) { if (e.target.id !== 'alert-inc') { hideAlertInc() } if (e.target.id !== 'alert-co') { hideAlertCo() } }
可选优化
如果你的提示div内部包含文字、关闭按钮、图标等子元素,上面的基础写法会出现「点击提示框内部子元素时误关闭提示」的问题——因为点击子元素时事件目标e.target是子元素,id和提示框id不匹配,会错误触发关闭逻辑。
更稳妥的写法是通过节点包含关系判断点击区域是否在提示框外部:
function hideAlertInc() { const incAlert = document.getElementById("alert-inc"); if (incAlert) incAlert.style.display = "none"; } function hideAlertCo() { const coAlert = document.getElementById("alert-co"); if (coAlert) coAlert.style.display = "none"; } document.onclick = function (e) { const incAlert = document.getElementById("alert-inc"); const coAlert = document.getElementById("alert-co"); // 点击目标不在成功提示节点及其所有子节点范围内时,关闭成功提示 if (incAlert && !incAlert.contains(e.target)) { hideAlertInc() } // 点击目标不在错误提示节点及其所有子节点范围内时,关闭错误提示 if (coAlert && !coAlert.contains(e.target)) { hideAlertCo() } }
内容的提问来源于stack exchange,提问作者xFragger
相关产品推荐
相关产品推荐

