本文主要介绍事件冒泡,和利用冒泡方法的事件代理机制。
根据浏览器的兼容性问题作出代码举例
事件冒泡就是在DOM中,父级元素与子集元素有相同事件时,触发子集元素会引发从子集开始往上的事件响应。
具体可以写多重包裹的div,并且所有元素添加相同的事件触发;检验触发子元素时,父元素的状态即可。
那么怎么取消冒泡机制呢?
不同的浏览器之间有差别,在此需要进行兼容性处理。如下两个方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<script>
window.onload = function(){
/*测试取消冒泡方法代码 */
var btn = document.getElementById('secondDiv');
btn.onclick = function(evnt){
var event = evnt||window.event;
if(event.stopPorpergation){ //FF下的处理
event.stopPorpergation();
}else{
event.cancelBubble = true;//IE下的处理
}
}
document.getElementById('firstDiv').onclick = function(){alert('hi~firstDiv');};
document.onclick = function(){alert('hi~body');};
}
</script>
</head>
<body>
<div id="firstDiv" style="background-color:red;width:300px;height:300px;">
The First DIV
<div id="secondDiv" style="background-color:blue;width:150px;height:150px;">
The Second DIV</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<script>
window.onload = bubble;
function bubble(){
document.getElementById("firstDiv").onmousedown = function(evnt){
var theEvent = evnt ? evnt : window.event;
alert("the First DIV's bubble");
stopBubble(theEvent);
}
document.getElementById("secondDiv").onmousedown = function(evnt){
var theEvent = evnt ? evnt : window.event;
alert("the Second DIV's bubble");
stopBubble(theEvent);
}
document.onmousedown = function(){
alert("the document bubble");
}
}
function stopBubble(evnt){
if(evnt.stopProragation){
evnt.stopPropagation();
}
else
evnt.cancelBubble = true;
}
</script>
</head>
<body>
<div id="firstDiv" style="background-color:red;width:300px;height:300px;">
The First DIV
<div id="secondDiv" style="background-color:blue;width:150px;height:150px;">
The Second DIV</div>
</div>
</body>
</html>
结果:
点击The Second DIV:没有反映
事件代理
什么是事件处理?
在传统的事件处理中,应按照需求为每一个元素添加或删除事件处理器。
通过事件代理可以把事件处理器添加到一个父级元素当中;
当多个元素的事件被触发时,利用冒泡机制将事件和与之对应的元素查找, 即可在仅在父类元素中处理多个事件。
这样有效地避免了多个事件处理器导致的内存泄露或者性能下降的问题。
事件处理怎么做?
利用冒泡机制,把事件从原始元素冒泡到DOM树最上层。
过程:事件处理器在一个元素上,等待一个事件从子集元素冒泡上来,并得知这个事件从那个元素开始:
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<script>
/*事件代理*/
window.onload = function editCell(e){
var target = getEventTarget(e);
if(target.tagName=='div')
{
target.style.backgroundColor = 'red';
}
}
function getEventTarget(e){ //获取目标元素函数
var e = e||window.e;
//target是FF下的对象,srcElement是IE下的,二者均可在chrome最新版使用
return e.target||e.srcElement;
}
</script>
</head>
<body>
<div>a1</div>
<a>a1</a>
<div>a2</div>
<a>a2</a>
<div>a3</div>
<a>a3</a>
<div>a4</div>
<a>a4</a>
</body>
</html>