事件冒泡和事件捕获

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>事件冒泡和事件捕获title>
    
     <style>
         #grandpa{
             width: 400px;
             height: 300px;
             border: 2px solid black;
         }
         #parent{
             width: 300px;
             height: 200px;
             background: yellow;
         }
         #child{
             width: 200px;
             height: 100px;
             background: red;
             border: 5px solid black;
         }
     style>
head>
<body>
    <div id="grandpa">
        爷爷
        <div id="parent">
            爸爸
            <div id="child">儿子div>
        div>
    div>
    <script>
        var grandpa=document.getElementById("grandpa");
        var parent=document.getElementById("parent");
        var child=document.getElementById("child");
        grandpa.addEventListener("click",function(){
            alert("我是爷爷");
        },false);//最后执行爷爷句柄
        parent.addEventListener("click",function(){
            alert("我是爸爸");
        },true);//当触发儿子的事件时,爸爸句柄先执行
        child.addEventListener("click",function(){
            alert("我是儿子");//触发儿子事件后,执行爸爸句柄后再执行儿子句柄
        },false);
    script>
body>
html>

你可能感兴趣的:(事件冒泡和事件捕获)