zoukankan      html  css  js  c++  java
  • 这样阻止事件冒泡

    做项目时 有时候会遇到如下需求

    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>
    

      好了 这样事件冒泡就被阻止了 想要的效果就实现了

  • 相关阅读:
    C++每次读取一行字符串输入(学习笔记) (转)
    Ubuntu使用Windows下的conio.h
    容斥原理、欧拉函数、phi
    UVa1635
    转:用STL中的vector动态开辟二维数组
    [转载]Vector用法(C++ Primer中文版)
    c++中vector的pair与make_pair的使用,双关键字排序
    uva12716 GCD XOR
    在 Ubuntu 14.04 中安装 Pepper Flash Player For Chromium
    Careercup
  • 原文地址:https://www.cnblogs.com/xingmi/p/2548286.html
Copyright © 2011-2022 走看看