转自https://blog.csdn.net/yimawujiang/article/details/86496936css
问题:js实现点击按钮时显示弹框,点击按钮及弹框之外的区域时隐藏弹框?ide
方案一:这个问题一般的办法是使用阻止事件冒泡来实现,代码以下(省略css):spa
<body> <button id="btn1" onclick="alertBoxFn();stopBubble()">打开弹窗</button> <div id="alertBox" onclick="stopBubble()"></div> </body> <script> function alertBoxFn(e) { alertBox.style.display = "block"; } function stopBubble(e){ var e=e||window.event; e.stopPropagation() } document.body.addEventListener('click', function() { alertBox.style.display = 'none' }) </script>
但这有一个弊端,就是若是页面上须要有多个按钮分别控制多个弹框,需求是点击按钮1时显示弹框1,点击按钮2时显示弹框2,同时隐藏弹框1。但结果倒是点击按钮2时,按钮1并不会隐藏。这是由于按钮2阻止了点击事件的冒泡,致使body元素的点击事件并无被触发。因而,这里咱们不能再使用阻止事件冒泡的方法了。.net
方案二:声明一个变量用来判断鼠标是否点击的是按钮或弹框。代码以下(省略css):code
<body> <button id="btn" onclick="alertBoxFn()">打开弹窗</button> <div id="alertBox" onclick="outside=false"></div> </body> <script> var outside=true function alertBoxFn(e) { outside=false alertBox.style.display = "block"; }
//如下两个方法用于判断是点击按钮和弹框,仍是弹框外面,若是点击弹框外面隐藏弹框,注document.body必需要在文档后面写,在head写documnet.body为null document.body.addEventListener('click', function() { outside=true },true) document.body.addEventListener('click', function() { if(outside){ alertBox.style.display = 'none' } }) </script>