1.冒泡机制:事件从DOM树的底层,层层往上传递,直至传递到DOM层的根节点。
教程(脚本之家):https://www.jb51.net/article/94399.htm
2.冒泡顺序:div>body>html>document>window;blur,focus,load,unload不能冒泡。
3.阻止冒泡:标准浏览器、IE浏览器
w3c:event.stopPropagation()
IE:event.cancelBubble = true
(与对应英文类似!)
4.案例:
<div id="father">
<button id="btn">点我</button>
</div>
<style>
#father {
width: 600px;
height: 600px;
background-color: red;
}
</style>
console.log('hello!');
var father = document.getElementById('father');
var btn = document.getElementById('btn');
btn.addEventListener('click', function (ev1) {
myTool.stopBubble(ev1);
alert('点击了按钮!');
});
father.addEventListener('click', function (ev2) {
myTool.stopBubble(ev2);
alert('点击了父标签!');
});
document.addEventListener('click', function () {
alert('点击了文档!');
})
上面的代码在调试的时候总出问题!每次明明引入了mytool就是提示这个函数没有定义!!!!我NMD累傻了!
var myTool = {
$: function (id) {
return typeof id === "string" ? document.getElementById(id) : null;
},
scroll: function () {
if (window.pageYOffset !== null) { //最新的浏览器
return {
//里面相当于字面量对象或JSON对象,是有区别的
"top": window.pageYOffset,
"left": window.pageXOffset
}
} else if (document.compatMode === 'CSS1Compat') { //W3C标准
return {
"top": document.documentElement.scrollTop,
"left": document.documentElement.scrollLeft
}
}
return {
"top": document.body.scrollTop,
"left": document.body.scrollLeft
}
},
show: function (ele) {
ele.style.display = 'block';
},
hide: function (ele) {
ele.style.display = 'none';
},
client: function () {
if (window.innerWidth !== null) { //最新的浏览器
return {
//里面相当于字面量对象或JSON对象,是有区别的
"width": window.innerWidth,
"height": window.innerHeight
}
} else if (document.compatMode === 'CSS1Compat') { //W3C标准
return {
"width": document.documentElement.clientWidth,
"height": document.documentElement.clientHeight
}
}
return {
"width": document.body.scrollWidth,
"height": document.body.scrollHeight
}
},
/*阻止冒泡*/
stopBubble: function (eve) {
if(eve && eve.stopPropagation){
eve.stopPropagation();
}else{ //IE678
eve.cancelBubble = true;
}
}
};