JS实现点击空白处弹窗消失
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>点击空白处弹窗消失</title> <style> *{ margin: 0; padding: 0; } #app{ width: 300px; margin: 40px auto; } .input-text{ width: 100%; box-sizing: border-box; } .content{ height: 300px; border: 1px solid black; } .hide{ display: none; } </style> </head> <body> <div id="app"> <input type="text" class="input-text"/> <div class="content hide"> <div> <button type="button">确定</button> </div> </div> </div> <script> //事件委托就是利用事件冒泡特性,给父元素绑定事件 //parent.contains(child) 判断是否是某个节点的子节点 //e.target 触发事件的源节点 document.onclick = function(e){ e = window.event || e; let parentApp = document.getElementById('app'); if(parentApp.contains(e.target)){ console.log("app元素内,移除.hide"); document.querySelectorAll('.content')[0].classList.remove("hide") }else{ console.log("app元素外,添加.hide"); document.querySelectorAll('.content')[0].classList.add("hide") } } //自定义contains方法 var cusContains = function(parNode,childNode){ //子节点不能是html或body标签 while (childNode && !/HTML|BODY/.test(childNode.nodeName)){ if (childNode == parNode){ return true; } childNode = childNode.parentNode; } return false; } </script> </body> </html>