事件冒泡和事件捕获以及解释target和currenttarget的区别

2023-05-31,,

冒泡捕获的区别是冒泡事件是先触发子元素事件,再触发父元素事件,这个是冒泡。捕获是先触发父元素事件,再触发子元素事件。简单的来说,冒泡的顺序是由内到外,捕获的顺序是由外到内
举例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#son{
width: 200px;
height: 200px;
background-color: yellow;
}
#father{
width: 400px;
height: 400px;
background-color: red;
}
</style>
</head>
<body>
<div id="father">
<div id="son">
</div>
</div>
</body>
<script>
var father=document.getElementById("father");
var son=document.getElementById("son");

function outSide(){
console.log("我是父元素事件")
}
function inSide(){
console.log("我是子元素事件")
}

//测试冒泡 执行结果为先出现我是子元素,再出现我是父元素,证明元素执行的顺序是由内到外
// son.addEventListener("click",inSide,false);
// father.addEventListener("click",outSide,false);
// 测试捕获 执行结果是先出现我是父元素,再出现我是子元素,证明元素的执行顺序是由外到内
son.addEventListener("click",inSide,true);
father.addEventListener("click",outSide,true);

</script>

</html>

阻止事件冒泡:

function load(){
console.log('body')
}
function cli(e){
console.log('div');
if ( e && e.stopPropagation ){
e.stopPropagation(); 
}
else{
window.event.cancelBubble = true;
return false;
}
}

需要注意,在一些特殊事件中,本身就屏蔽了事件的冒泡

mouseout和mouseover 支持事件冒泡

mouseenter和mouseleave 则会自动阻止事件冒泡

target和currenttarget的区别 target指的是事件的真正触发者,currenttarget指的是事件的监听者,当不存在冒泡或者捕获的情况下,通常两者指向的对象为同一个,但是如果存在冒泡或者捕获,

就会指向各自所产生的对象

代码举例

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#out{
width: 400px;
height:400px;
background-color:yellow;
}

#in{
width: 200px;
height:200px;
background-color:red;

}
</style>
</head>
<body>

<div id="out">
<div id="in"></div>
</div>

</body>
<script>
var out=document.getElementById("out");
var inner=document.getElementById("in");

out.addEventListener("click",function(e){
console.log("我在外面");
console.log(e.target);
console.log(e.currentTarget);
},false);
inner.addEventListener("click",function(e){
console.log("冒泡了");
console.log(e.target);
console.log(e.currentTarget);

},false);

此时点击out元素时,因为不触发冒泡事件,所以e.target和e.currentTarget的输出结果均为id=out的div,也就是大盒子触发了监听事件。

但是当点击in元素的时候,测触发冒泡,此时in元素的 e.target和e.currentTarget相同(因为原本点击的就是In元素),但因为冒泡,其父元素out也会产生监听事件

而此时 out元素的 e.target 为 in 元素,因为确实点击的是 in元素(target指向真正的触发元素),而e.currentTarget输出则为out元素(产生监听的事件的元素)。

稍微自己总结了下,也不知道对不对:在通常情况下 e.target和e.currentTarget相同而在产生了冒泡或者捕获的元素中,非点击元素的 e.target和e.currentTarget不同.

事件冒泡和事件捕获以及解释target和currenttarget的区别的相关教程结束。

《事件冒泡和事件捕获以及解释target和currenttarget的区别.doc》

下载本文的Word格式文档,以方便收藏与打印。