JS4 -- 事件流(冒泡和捕获)

1.事件委托或事件代理

var oUl = document.getElementById('ul').addEventListener('click',function(){})

https://www.cnblogs.com/liugang-vip/p/5616484.html

 

事件捕获(网景)

var oDiv = document.getElementById('div').addEventListener("click",function() {},true)

自外向内(从上级至下级),父级元素向子。。。元素

 

事件冒泡(IE -> firefox、chrome、safari、opera)

冒泡:自内向外(从下至上),子元素向父。。。元素

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    #father{
        width: 1000px;
        height: 200px;
        background: rgba(255,0,0,.4);
    }
    #son{
        width: 200px;
        height: 200px;
        background: rgba(0,255,0,.4);
    }
    </style> 
</head>
<body>
    <div id="father">
        <div id="son">我是儿子</div>
    </div>
    <script>
        // (1)事件冒泡
        // document.getElementById('father').onclick = function() {
        //     alert('father')
        // }
        // document.getElementById('son').onclick = function() {
        //     alert('son')
        // }
     //点击子元素打印 =》 son到father
     // 阻止冒泡: window.event? window.event.cancelBubble = true : e.stopPropagation();
// (2)事件捕获 document.getElementById('father').addEventListener("click",function(e){ alert('father') },true) document.getElementById('son').addEventListener("click",function(e){ alert('son') },true)
     //点击子元素打印 => father到son
</script> </body> </html>

 

 

 

 

 

JavaScript捕获和冒泡探讨

posted @ 2018-08-23 00:01  Yo!  阅读(291)  评论(0编辑  收藏  举报