javascript冒泡和默认事件
对于javascript的冒泡,我一直误解它了,
冒泡,即是从底层往外blow blow blow ...
惭愧的是,我一直以为阻止冒泡是阻止父元素往子元素传递事件……
贴上一串代码以便往后回顾!
1 <script type="text/javascript"> 2 window.onload=function(){ 3 var a=document.getElementById("a"); 4 var b=document.getElementById("b"); 5 var c=document.getElementById("c"); 6 var c=document.getElementById("d"); 7 8 a.onclick=function(e){ 9 this.style.background="#000"; 10 }; 11 12 b.onclick=function(e){ 13 this.style.background="#ccc"; 14 //阻止事件冒泡 15 window.event.cancelBubble = true;//IE8以下 16 e.stopPropagation(); 17 }; 18 19 d.onmousedown=function(e){ 20 //阻止默认事件,比如在chrome下图片有拖拽默认行为 21 window.event.returnValue = false; 22 e.preventDefault(); 23 } 24 } 25 26 27 28 </script>

1 <div id="a" style="width:300px;height:300px;background:red;overflow:hidden;"> 2 <div id="b" style="width:200px;height:200px;background:green;margin:50px 0 0 50px;overflow:hidden;"> 3 <div id="c" style="width:100px;height:100px;background:yellow;margin:50px 0 0 50px;overflow:hidden;"> 4 <img src="240x240.jpg" width="50" height="50" id="d" /> 5 </div> 6 </div> 7 </div>
另一个例子:
<script type="text/javascript"> window.onload=function(){ document.getElementById("test").addEventListener('click',function(e){ alert('aaaa') },false); document.getElementById("test1").addEventListener('click',function(e){ alert('bbb') e.stopPropagation(); },false) } </script>
<style type="text/css"> #test1{width:100px;height:100px;background:#ff0} #test2{width:100px;height:100px;background:#ff0} </style> <div id="test" style="width:100px;height:100px;background:#f60;padding:20px;"> <div id="test1"></div> </div>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?