1.事件流概念:
捕获阶段:从往里走的阶段;
目标阶段:到达目标了;
冒泡阶段:从目标离开,往外走;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>作用域</title> <style> #grandfa { width: 600px; height: 600px; border: 1px solid #000; } #father { width: 400px; height: 400px; border: 1px solid #000; } #son { width: 200px; height: 200px; border: 1px solid #000; } </style> </head> <body> <div id="grandfa"> <div id="father"> <div id="son"></div> </div> </div> <script> var grandfa = document.getElementById(‘grandfa‘) var father = document.getElementById(‘father‘) var son = document.getElementById(‘son‘) grandfa.onclick = function () { console.log(‘grandfa点击事件‘) } father.onclick = function () { console.log(‘father点击事件‘) } son.onclick = function () { console.log(‘son点击事件‘) } </script> </body> </html>
2.事件委托:本来是自己做的事,委托给父级元素
var ul=document.getElementById(‘ul‘) ul.addEventListener(‘click‘,fn,false) function fn(e){ console.log(e.target.innerText ) }
3.e.stopPropagation(); 阻止事件传播
son.onclick = function (e) { console.log(‘son点击事件‘) e.stopPropagation() }
4.e.proventDefaut() 阻止默认行为
var box = document.getElementById(‘box‘) box.addEventListener(‘click‘,function(e){ console.log(1) e.preventDefault; // return false; //在addEventListener不能使用return false来阻止默认行为 })
原文:https://www.cnblogs.com/zhaodz/p/11618920.html