要求:点击按钮时,下拉框显示;点击页面其他部分时,下拉框消失;
1. 不靠谱代码
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 #div1 { 8 width: 400px; 9 height: 300px; 10 background-color: #ccc; 11 display: none; 12 } 13 </style> 14 <script> 15 window.onload = function () { 16 var oBtn = document.getElementById("btn1"); 17 var oDiv = document.getElementById("div1"); 18 19 oBtn.onclick = function () { 20 oDiv.style.display = "block"; 21 }; 22 document.onclick = function () { 23 oDiv.style.display = "none"; 24 }; 25 } 26 </script> 27 </head> 28 <body> 29 <input id="btn1" type="button" value="show" /> 30 <div id="div1"></div> 31 </body> 32 </html>
不靠谱原因:当点击按钮时,(1)点击事件在btn上触发并执行,此时下拉框显示;(2)事件一直向上冒泡,并遇到了定义在document上的点击事件,触发并执行,此时下拉框不显示;
2. 解决方案 --- 组织事件冒泡(event.cancelBubble = true)
1 oBtn.onclick = function (event) { 2 oDiv.style.display = "block"; 3 event.cancelBubble = true; 4 };