关于javascript冒泡与默认事件的使用详解
更新时间:2013年05月14日 16:21:33 作者:
本篇文章是对javascript中冒泡与默认事件的使用进行了详细的分析介绍,需要的朋友参考下
对于javascript的冒泡,我一直误解它了,
冒泡,即是从底层往外blow blow blow ...
惭愧的是,我一直以为阻止冒泡是阻止父元素往子元素传递事件……
贴上一串代码以便往后回顾!
复制代码 代码如下:
<script type="text/javascript">
window.onload=function(){
var a=document.getElementById("a");
var b=document.getElementById("b");
var c=document.getElementById("c");
var c=document.getElementById("d");
a.onclick=function(e){
this.style.background="#000";
};
b.onclick=function(e){
this.style.background="#ccc";
//阻止事件冒泡
window.event.cancelBubble = true;//IE8以下
e.stopPropagation();
};
d.onmousedown=function(e){
//阻止默认事件,比如在chrome下图片有拖拽默认行为
window.event.returnValue = false;
e.preventDefault();
}
}
</script>
复制代码 代码如下:
Html部分
<div id="a" style="width:300px;height:300px;background:red;overflow:hidden;">
<div id="b" style="width:200px;height:200px;background:green;margin:50px 0 0 50px;overflow:hidden;">
<div id="c" style="width:100px;height:100px;background:yellow;margin:50px 0 0 50px;overflow:hidden;">
<img src="240x240.jpg" width="50" height="50" id="d" />
</div>
</div>
</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>
相关文章
Unity中的InitializeOnLoad特性实践深入解析
这篇文章主要为大家介绍了Unity中的InitializeOnLoad特性实践深入解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-05-05利用TaskManager爬取2万条代理IP实现自动投票功能
话说某天心血来潮想到一个问题,朋友圈里面经常有人发投票链接,让帮忙给XX投票,以前呢会很自觉打开链接帮忙投一票。可是这种事做多了就会考虑能不能使用工具来进行投票呢,身为一名程序猿决定研究解决这个问题。感兴趣的朋友一起学习吧2015-09-09
最新评论