對於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>