由于习惯于jquery的方便操作,往往让我们慢慢淡忘了原生js应有的功能和属性,今天重温一下事件冒泡和捕获问题。
冒泡:从内向外,如:div > body > html (不同浏览器稍有不同)
捕获:从外向内,如:html > body > div
阻止冒泡或捕获:e.stopPropagation() || e.cancelBubble = true;
例子,具体也可以随意修改予以测试:
<!DOCTYPE HTML>
<html><head><meta charset="UTF-8"><title>冒泡捕获</title><link href="css/main.css"/><style type="text/css"></style></head><body><div id="container"><div id="level1" style="border:5px solid green;"><div id="level2" style="border:1px solid #ccc;margin:20px;">jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br>jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br>jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br>jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br>jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br>jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br>jfsdkljfklsdjklf <br><br><br><br><br><br><br><br><br><br><br></div></div></div><script>//标准浏览器,支持冒泡和捕获,ie91011document.addEventListener('click', function(e){console.log('document');e.stopPropagation();}, false); // 如果此处为true,则在从外向内捕获过程终止document.getElementById('level1').addEventListener('click', function(){console.log('level1');}, false);document.getElementById('level2').addEventListener('click', function(){console.log('level2');}, false);//<=ie8,只支持冒泡document.attachEvent('onclick', function(){console.log('document');});document.getElementById('level1').attachEvent('onclick', function(e){alert('level1');e.cancelBubble = true;});document.getElementById('level2').onclick = function(e){e = e || window.event;alert('level1');e.cancelBubble = true;};document.getElementById('level2').attachEvent('onclick', function(e){alert('level2');// e.cancelBubble = true;});</script></body>
</html>