事件传播
—当行为发生,改行为会按照父级的顺序向上触发,直到window
事件流机制
1.捕获阶段
从window开始,向下触发,直到目标元素
2.目标阶段
准确触发事件的元素
3.冒泡阶段
从目标元素开始,逐级向上,直到window
可以在冒泡阶段触发事件 ,也可以在捕获阶段触发
默认是冒泡,可通过addEventListener改变,传递第三个参数true改为捕获阶段触发事件
事件源.addEventListener(事件类型,function(){},true/false)
true——捕获阶段,false是默认值——冒泡阶段
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .grandfather { width: 300px; height: 300px; background-color: pink; margin: 50px auto; } .father { width: 200px; height: 200px; background-color: rgb(255, 51, 0); } .son { width: 100px; height: 100px; background-color: rgb(255, 255, 0); } </style> </head> <body> <div class="grandfather"> <div class="father"> <div class="son"></div> </div> </div> <script> var son = document.querySelector(".son"); var father = document.querySelector(".father"); var grandfather = document.querySelector(".grandfather"); //完整的事件流机制 //捕获阶段 father.addEventListener( "click", function () { alert("father"); }, true ); grandfather.addEventListener( "click", function () { alert("grandfather"); }, true ); document.body.addEventListener( "click", function () { alert("body"); }, true ); document.documentElement.addEventListener( "click", function () { alert("html"); }, true ); document.addEventListener( "click", function () { alert("document"); }, true ); window.addEventListener( "click", function () { alert("window"); }, true ); // 目标阶段 准确触发事件 son.addEventListener( "click", function () { alert("son"); }, true ); //冒泡阶段 father.onclick = function () { alert("father"); }; document.body.onclick = function () { alert("body"); }; // //同一事件类型才会触发 // document.documentElement.ondblclick = function () { // alert("html"); // }; window.onclick = function () { console.log("window"); }; </script> </body> </html>
阻止事件传播(阻止事件冒泡)
事件传播到btn就不再传播
btn.onclick = function (e) {
e.stopPropagation();
};
阻止默认行为
比如:表单 提交时 会默认刷新
语法:
1.事件对象.preventDefault()
2.return false