Dom事件流

dom的结构是一个倒立的树状结构。当一个html元素触发事件时,事件会在dom的根节点和触发事件的元素节点之间传播,中间的节点都会收到该事件。

捕获:div元素触发事件时,事件先从根节点document→html→body→div这个顺序传播。(给这四个节点绑定事件,事件依次触发的顺序);

冒泡:div元素触发事件时,事件从div→body→html→document这个顺序传播。

dom事件流:先捕获,再冒泡。从document开始,到document结束形成一个完整的事件流。

 

其实工作中用的最多的也就是阻止冒泡和给父元素绑定事件来监听子元素。

阻止冒泡:stopPropagation();IE cancelBubble = true;

阻止默认行为:preventDefault();IE window.event.returnValue = false;

(到这就完事了,也没啥玩意了)

————可————————爱————————分———————————割——————————线———————-——————————————

标准实现方式使用关键词addEventListener。   element.addEventListener(eventType, fn, false),第三个参数false表示冒泡,true表示捕获。

我把这个仁兄的例子拿过来了(原谅我的懒,让我复制粘贴一下),可以看一下效果。http://www.cnblogs.com/qiongmiaoer/p/4566917.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>bubble event</title>
    <style type="text/css">
        body{margin:0;}
        #one{
            width:500px;
            height:300px;
            background:rgb(255,0,0);
        }
        #two{
            width:400px;
            height:260px;
            background:rgb(255,50,50);
        }
        #three{
            width:300px;
            height:240px;
            background:rgb(255,100,100);
        }
        #four{
            width:200px;
            height:200px;
            background:rgb(255,150,150);
        }
    </style>
</head>
<body>
<div id='one'>
    one
    <div id='two'>
        two
        <div id='three'>
            three
            <div id='four'>
                four
            </div>
        </div>
    </div>
</div>

<script>
    var one = document.getElementById('one');
    var two = document.getElementById('two');
    var three = document.getElementById('three');
    var four = document.getElementById('four');

    var useCapture = false; //false为冒泡获取【目标元素先触发】    true为捕获获取【父级元素先触发】
    one.addEventListener('click', function() {
        console.log('one');
    }, useCapture);
    two.addEventListener('click', function() {
        console.log('two');
    }, useCapture);
    three.addEventListener('click', function() {
        console.log('three');
    }, useCapture);
    four.addEventListener('click', function() {
        console.log('four');
    }, useCapture);
    /*
     false
     冒泡
     点击four div
     输出结果:four three two one

     true
     捕获
     点击four div
     输出结果: one two three four
     */
</script>
</body>
</html>

 

posted on 2017-04-12 12:11  热爱游戏享受生活  阅读(433)  评论(0编辑  收藏  举报