js 冒泡事件與解決冒泡事件

事件冒泡 :當(dāng)一個(gè)元素接收到事件的時(shí)候 會(huì)把他接收到的事件傳給自己的父級(jí),一直到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、非標(biāo)準(zhǔn)的IE方式:window.event.cancelBubble=true; 這里的cancelBubble是 IE事件對(duì)象的屬性,設(shè)為true就可以了(IE特有的,谷歌支持,火狐不支持)
my$("div2").onclick=function () {console.log(this.id);window.event.cancelBubble=true;};
為了兼容解決事件冒泡的方式:
function stopBubble(e) {//如果提供了事件對(duì)象,則這是一個(gè)非IE瀏覽器if (e && e.stopPropagation)//因此它支持W3C的stopPropagation()方法e.stopPropagation();else//否則,我們需要使用IE的方式來(lái)取消事件冒泡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)};
本文完~

評(píng)論
圖片
表情
