事件的冒泡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box1{
            width: 200px;
            height: 200px;
            background-color: yellowgreen;
        }
        #s1{
            background-color: yellow;
        }
    </style>
    <script>
        window.onload=function(){

            /*------事件的冒泡(Bubble)------
                -所谓的冒泡值得就是事件的想上传到,当都带元素上的事件被触发时,其祖先元素的相同时间也会被触发
                -在开发中大部分情况冒泡都是有用的,如果不希望发生时间冒泡可以通过事件对象来取消冒泡

*/

//----------------------------------------------------------------------------
            // 为s1绑定一个单击响应函数
            var s1=document.getElementById("s1");
            s1.onclick=function(event){
                event=event||window.event;
                console.log("我是span的单击响应函数");

                // 取消冒泡
                // 乐意将事件对象的cancelBubble设置为true,即可取消冒泡
                event.cancelBubble = true;
            };
//-------------------------------------------------------------------------------
            // 为box1绑定一个单击响应函数
            var box1=document.getElementById("box1");
            box1.onclick=function(event){
            event = event || window.event;
                console.log("我是div的单击响应函数");
                event.cancelBubble = true;

            };

//-------------------------------------------------------------------------------
            // 为body绑定一个单击响应函数
            document.body.onclick=function(){
                console.log("我是body的单击响应函数");
            };

        };
    </script>
</head>
<body>
    <div id="box1">我是一个快
        <span id="s1">我是span</span>
    </div>
    
</body>
</html>

点击space

 

点击div

 

 点击body主体

 

posted @ 2020-12-01 16:02  Hhhr  阅读(71)  评论(0编辑  收藏  举报