js 冒泡事件与解决冒泡事件

事件冒泡 :当一个元素接收到事件的时候 会把他接收到的事件传给自己的父级,一直到window 。
代码:
<div id="div1"><div id="div2"><div id="div3">div>div>div><style>#div1{width: 300px;height: 200px;background-color: red;}#div2{width: 250px;height: 150px;background-color: green;}#div3{width: 200px;height: 100px;background-color: blue;}style>my$("div1").onclick=function () {console.log(this.id);};//div3 div2 div1my$("div2").onclick=function () {console.log(this.id);};//div2 div1my$("div3").onclick=function () {console.log(this.id);};//div1
my$("div3").onclick=function (e) {console.log(this.id);e.stopPropagation();};
2、非标准的IE方式:window.event.cancelBubble=true; 这里的cancelBubble是 IE事件对象的属性,设为true就可以了(IE特有的,谷歌支持,火狐不支持)
my$("div2").onclick=function () {console.log(this.id);window.event.cancelBubble=true;};
为了兼容解决事件冒泡的方式:
function stopBubble(e) {//如果提供了事件对象,则这是一个非IE浏览器if (e && e.stopPropagation)//因此它支持W3C的stopPropagation()方法e.stopPropagation();else//否则,我们需要使用IE的方式来取消事件冒泡window.event.cancelBubble = true;}my$("div2").onclick = function (e) {console.log(this.id);stopBubble(e)};my$("div3").onclick = function (e) {console.log(this.id);stopBubble(e)};
本文完~

评论
