捕获、冒泡
先捕获,后冒泡;先窗口,后元素,再窗口;大小大;
useCapture
:默认是false 冒泡,true为捕获
element.addEventListener(event, function, useCapture)
e.stopPropagation()
// 阻止冒泡和捕获 e.stopImmediatePropagation()
// 既能阻止冒泡和捕获,也能阻止当前节点上其他同类型事件的触发
<!DOCTYPE html>
<html>
<head>
<title>event</title>
</head>
<body>
<h3>冒泡</h3>
<div id="obj1" style="background-color: #ffcccc;">
obj1
<div id="obj2" style="background-color: #ccffcc;margin-left:20px;">obj2
<div id="obj3" style="background-color: #ccccff;margin-left:20px;">obj3</div>
</div>
</div>
<br />
<h3>捕获</h3>
<div id="div1" style="background-color: #ffcccc;">
div1
<div id="div2" style="background-color: #ccffcc;margin-left:20px;">div2
<div id="div3" style="background-color: #ccccff;margin-left:20px;">div3</div>
</div>
</div>
<br />
<h3>stopImmediatePropagation</h3>
<div id="block1" style="background-color: #ffcccc;">
block1
<div id="block2" style="background-color: #ccffcc;margin-left:20px;">block2
<div id="block3" style="background-color: #ccccff;margin-left:20px;">block3</div>
</div>
</div>
<script type="text/javascript">
//addEventListener 监听冒泡
document.getElementById('obj1').addEventListener('click', function (e) {
console.log('obj1');
});
document.getElementById('obj2').addEventListener('click', function (e) {
console.log('obj2');
// e.stopPropagation() // 阻止冒泡和捕获
})
document.getElementById('obj3').addEventListener('click', function () {
console.log('obj3');
})
// element.addEventListener(event, function, useCapture) , useCapture:默认是false 冒泡,true为捕获
//addEventListener 监听冒泡
document.getElementById('div1').addEventListener('click', function (e) {
console.log('div1');
}, true);
document.getElementById('div2').addEventListener('click', function (e) {
console.log('div2');
// e.stopPropagation() // 阻止冒泡和捕获
}, true);
document.getElementById('div3').addEventListener('click', function () {
console.log('div3');
}, true);
document.getElementById('block1').addEventListener('click', function (e) {
console.log('block1');
}, true);
document.getElementById('block2').addEventListener('click', function (e) {
console.log('block2');
e.stopImmediatePropagation()// 既能阻止冒泡和捕获,也能阻止当前节点上其他同类型事件的触发
}, true);
document.getElementById('block2').addEventListener('click', function (e) {
console.log('block2 again');
}, true);
document.getElementById('block3').addEventListener('click', function () {
console.log('block3');
}, true);
</script>
</body>
</html>