事件冒泡和捕获

84 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="demo" style="width: 300px;height: 300px;background: red;">
    <button id="btn">demo</button>
</div>

<script>
    let demo = document.querySelector('#demo')
    let btn = document.querySelector('#btn')

    // 事件冒泡 由子级向父级
    btn.onclick = function(e){
        e.stopPropagation();
        console.log(111);
    }
    demo.onclick = function(){
        console.log(222);
    }
    document.body.onclick = function(){
        console.log(333);
    }


    // 捕获  由父级向子级
    btn.addEventListener('click',function(e){
        console.log(111);
    },true)
    demo.addEventListener('click',function(){
        console.log(22);
    },true)
    document.body.addEventListener('click',function(){
        console.log(33);
    },true)
</script>
</body>
</html>