js中addEventListener中第3个参数

时间:2023-03-08 20:48:40

addEventListener中的第三个参 数是useCapture, 一个bool类型。当为false时为冒泡获取(由里向外),true为capture方式(由外向里)。

    1. <div id="id1" style="width:200px; height:200px; position:absolute; top:100px; left:100px; background-color:blue; z-index:4">
    2. <div id="id2" style="width:200px; height:200px; position:absolute; top:20px; left:70px; background-color:green; z-index:1"></div>
    3. </div>
    1. document.getElementById('id1').addEventListener('click', function() { console.log('id1');}, false);
    2. document.getElementById('id2').addEventListener('click', function() { console.log('id2');}, false);
    1. document.getElementById('id1').addEventListener('click', function() { console.log('id1');}, false);
    2. document.getElementById('id2').addEventListener('click', function() { console.log('id2');}, false);

点击div时会根据useCapture参数来运行对应的事件。