• 这样阻止事件冒泡


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

    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>
    

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

  • 相关阅读:
    如何用nodejs创建一个proxy 服务
    企业包分发-应用内安装时碰到的问题
    React-Native与Weex的比较
    前端炫酷动画展示利器(lottie)
    记录一个web开发工具集网页
    git 和 远程分支关联
    reference to 'X' is ambiguous 解决
    mac 下解压 .bin文件
    fabric 集成trello
    ES6 对象的创建及操作
  • 原文地址:https://www.cnblogs.com/xingmi/p/2548286.html
Copyright © 2020-2023  润新知