做项目时 有时候会遇到如下需求
1 点击某个元素 下面隐藏的元素就出现
2 点击除这个元素外任何一个地方 这个元素都隐藏掉
3再次点击时再展开 如此反复
编写是代码如下
<code> <!doctype html> <html> <head>冒泡测试</head> <body> <div id="checkthis" style="wIDth:100px; height:100px; background:#555"> <span id="clickthis" style="display:block; 100%; height:100%;">点击我显示下面文本</span> </div> <p id="getText" style="display:none">234242342342342423423423</p> <script> clickthis.onclick = function(){ getText.style.cssText = "display:block;"; } document.body.onclick = function(){ getText.style.cssText = "display:none;"; } </script> </body> </html>` </code>
运行测试 发现奇怪了 随便怎样点击这个元素 下面隐藏的元素都不会出来 其实这里就是事件冒到了body这。点击了div冒泡到了body 执行函数 所以下面的p元素一直是隐藏状态
我们要阻止事件的冒泡 就要改变代码
代码如下
<code> <!doctype html> <html> <head>冒泡测试</head> <body> <div id="checkthis" style="wIDth:100px; height:100px; background:#555"> <span id="clickthis" style="display:block; 100%; height:100%;">点击我显示下面文本</span> </div> <p id="getText" style="display:none">234242342342342423423423</p> <script> clickthis.onclick = function(e){ e = window.event||event; sprint.innerHTML = "你点击的是span"; getText.style.cssText = "display:block;"; if(document.all){ e.cancelBubble = true;/*IE*/ }else{ e.stopPropagation();/*chrome firefox..*/ } } document.body.onclick = function(){ getText.style.cssText = "display:none;"; } </script> </body> </html>` </code>
好了 这样事件冒泡就被阻止了 想要的效果就实现了