Binding and event bubbling event API's

table of Contents

  • Both methods events bound
  • Event binding code compatible
  • Binding difference events
  • Unbundling
  • Binding events tied to reconciliation event code compatible
  • Event bubbling
  • Stop event bubbling
  • Three stages of the event
  • For the same elements in different registration events, pointing to the same event handler

Binding elements of both approaches

  • The first: addEventListener ( 'event type', the event handler, false) ----- Google support Firefox, IE8 does not support
  • attachEvent ( 'band on the event type', the event handler) ----- Google does not support Firefox, IE8 support
<body>
    <input type="button" value="按钮" id="btn">
    <script>
        var btn = document.getElementById('btn');
        //为按钮绑定点击事件: DOM中,只有一种,但是不兼容,所以有两种
        //第一种:addEventListener('事件类型', 事件处理函数, false)-----谷歌火狐支持,IE8不支持
        //参数1: 事件的类型----也就是事件的名字,没有on
        //参数2:  事件处理函数----也就是函数(命名函数或匿名函数)
        //参数3:  Boolean类型,暂时为false
        //第二种: attachEvent('带on的事件类型',事件处理函数)-----谷歌火狐不支持,IE8支持
        //参数1: 事件类型----带on
        //参数2: 事件处理函数-----函数(命名或匿名)


        btn.addEventListener('click', function() {
            console.log('明智之举');
        }, false);
        btn.addEventListener('click', function() {
            console.log('作词:许嵩');
        }, false);
        btn.addEventListener('click', function() {
            console.log('作曲:许嵩');
        }, false);
        btn.addEventListener('click', function() {
            console.log('演唱:许嵩');
        }, false);

        // btn.attachEvent('onclick', function() {
        //     console.log('明智之举');
        // });
        // btn.attachEvent('onclick', function() {
        //     console.log('如约而至');
        // });
        // btn.attachEvent('onclick', function() {
        //     console.log('许嵩');
        // });
    </script>
</body>

Event binding code compatible

 //为任意一个元素,绑定任意事件    任意元素, 事件的类型,事件处理函数
        function addEventListener(element, type, fn) {
            if (element.addEventListener) { //判断这个浏览器是否支持这个方法
                element.addEventListener(type, fn, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + type, fn); //element.attachEvent('onclick',function(){})
            } else {
                element['on' + type] = fn; // element.onclick = function() {}
            }
        }

Event Binding difference

Same point

  • Elements that can bind events

    difference

  • Method name is not the same
    • addEventListener
    • attachEvent
  • Not the same as the number of parameters
    • There are three parameters addEventListener
    • attachEvent only two parameters
  • Browser support is not the same
    • addEventListener Google, Firefox, IE11 support, IE8 does not support
    • attachEvent IE does not support, Google, Firefox, IE11 does not support
  • Different this
    • addEventListener in this refers to the current object binding events
    • attachEvent in this refers to the window
  • Different types of events
    • addEventListener is not on the event type
    • attachEvent the event types on

Unbundling

Note : binding events in what way, it unbundling event in what way

The first

  • Object .on event name = ------------ event handler binding events
  • Object .on event name = null; ------------- unbundling event
   //点击第二个按钮,解除第一个按钮的绑定事件
        var btn = document.getElementById('btn');
        var btn1 = document.getElementById('btn1');
        btn.onclick = function() {
            console.log('Worth it');
        }
        btn1.onclick = function() {
            //解绑事件
            btn.onclick = null;
        }

The second

  • Object .addEventListener ( 'event type', named function, false) ---------- binding events
  • Object .removeEventListener ( 'event type', named function, false) ------- unbinding event
        var btn = document.getElementById('btn');
        var btn1 = document.getElementById('btn1');

        function f3() {
            console.log('明智之举');
        }

        function f4() {
            console.log('作词:许嵩');
        }
        btn.addEventListener('click', f3, false);
        btn.addEventListener('click', f4, false);


        btn1.onclick = function() {

            //这种方式解绑的时候需要使用命名函数
            btn.removeEventListener('click', f4, false);
        }

The third

  • Object .attachEvent ( 'band on the event type' of named function);
  • Object .detachEvent ( 'band on the event type' of named function);
        var btn = document.getElementById('btn');
        var btn1 = document.getElementById('btn1');

        function f3() {
            console.log('明智之举');
        }

        function f4() {
            console.log('作词:许嵩');
        }
 btn.attachEvent('onclick', f3);
        btn.attachEvent('onclick', f4);

        btn1.onclick = function() {
            btn.detachEvent('onclick', f3);
        };

Binding events tied to reconciliation time code compatible

<input type="button" value="歌曲" id="btn">
<input type="button" value="清空歌曲" id="btn1">

<body>
    <script src='common.js'></script>
    <script>
        //绑定事件的兼容代码
        function addEventListener(element, type, fn) {
            if (element.addEventListener) {
                element.addEventListener(type, fn, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + type, fn);
            } else {
                element['on' + type] = fn;
            }
        }
        //解绑事件的兼容代码
        function removeEventListener(element, type, fnName) {
            if (element.removeEventListener) {
                element.removeEventListener(type, fnName, false);
            } else if (element.detachEvent) {
                element.detachEvent('on' + type, fnName);
            } else {
                element['on' + type] = null;
            }
        }
        //test
        function f1() {
            console.log('明智之举');
        }

        function f2() {
            console.log('作词:许嵩');
        }
        addEventListener(my$("btn"), "click", f1);
        addEventListener(my$("btn"), "click", f2);
        my$("btn1").onclick = function() {
            removeEventListener(my$("btn"), "click", f1);
        };
    </script>

Event bubbling

Multiple elements are nested, hierarchical relationships, these elements are registered in the same event, if the event inside the element is triggered, the event is triggered outside elements automatically

      <style>
        #dv1 {
            width: 300px;
            height: 400px;
            background-color: #def;
        }
        
        #dv2 {
            width: 250px;
            height: 350px;
            background-color: #edf;
        }
        
        #dv3 {
            width: 200px;
            height: 300px;
            background-color: #fed;
        }
    </style>
</head>

<body>
    <div id="dv1">
        <div id="dv2">
            <div id="dv3"></div>
        </div>
    </div>
    <script>
        //事件冒泡:多个元素嵌套,有层次关系,这些元素都注册了相同的事件,如果里面的元素的事件触发了,外面的元素的该事件自动触发   
        var dv1 = document.getElementById('dv1');
        var dv2 = document.getElementById('dv2');
        var dv3 = document.getElementById('dv3');

        dv1.onclick = function() {
            console.log('dv1');//dv1
        }
        dv2.onclick = function() {
            console.log('dv2');//dv2 dv1
        }
        dv3.onclick = function() {
            console.log('dv3');//dv3 dv2 dv1
        }
    </script>

Stop event bubbling

  1. window.event.cancelBubble = true; // Google, IE8 supports, but does not support Firefox
  2. e.stopPropagation (); // Google, Firefox support, but does not support IE8
<style>
        #dv1 {
            width: 300px;
            height: 400px;
            background-color: #def;
        }
        
        #dv2 {
            width: 250px;
            height: 350px;
            background-color: #edf;
        }
        
        #dv3 {
            width: 200px;
            height: 300px;
            background-color: #fed;
        }
    </style>
</head>

<body>
    <div id="dv1">
        <div id="dv2">
            <div id="dv3"></div>
        </div>
    </div>
    <script>
        var dv1 = document.getElementById('dv1');
        var dv2 = document.getElementById('dv2');
        var dv3 = document.getElementById('dv3');
        // 在事件被触发时会产生一个事件处理对象参数
        //如何阻止事件冒泡
        //1. window.event.cancelBubble = true;//谷歌,IE8支持,但火狐不支持
        //2.  e.stopPropagation();//谷歌、火狐支持,但是IE8不支持
        dv1.onclick = function() {
            console.log(this.id);
        }
        dv2.onclick = function(e) { //这里的e就是事件触发时产生的事件处理对象参数
            console.log(this.id);
            //阻止事件冒泡
            e.stopPropagation();
        }
        dv3.onclick = function() {
            console.log(this.id);
            //阻止事件冒泡
            window.event.cancelBubble = true;
        }
    </script>

</body>

Three stages of the event

  • 1 indicates that the event capturing phase ----------> outward from within
  • Stage 2 represents an event goal
  • 3 indicates that the event bubbling phase ----------> From the inside out
  • Case
 <style>
        #dv1 {
            width: 300px;
            height: 400px;
            background-color: #def;
        }
        
        #dv2 {
            width: 250px;
            height: 350px;
            background-color: #edf;
        }
        
        #dv3 {
            width: 200px;
            height: 300px;
            background-color: #fed;
        }
    </style>
</head>

<body>
    <div id='dv1'>
        <div id="dv2">
            <div id="dv3"></div>
        </div>
    </div>
    <script>
     
        //同时注册点击事件
        var objs = [document.getElementById('dv1'),
            document.getElementById('dv2'),
            document.getElementById('dv3')
        ];


        //遍历注册事件
        objs.forEach(function(ele) { //传一个参数的时候,这个参数是元素
            //为每个元素绑定事件;
            //   ele.addEventListener('click', function() {
            //     console.log(this.id + '--------->' + window.event.eventPhase);
            // }, false);
            ele.addEventListener('click', function() {
                console.log(this.id + '--------->' + window.event.eventPhase);
            }, true);
        });

        //array.forEach(function(数组当前项的值, 数组当前的索引,数组对象本身){

        //});
    </script>
  • to sum up
            为元素绑定事件
            addEventLinstener('没有on的事件类型',事件处理函数,控制事件阶段的)
            false------>表示事件冒泡阶段(从内向外 或者 从上到下)
            true-------> 表示事件捕获阶段(从外向内 或者 从下到上)
            事件触发的过程中可能会出现事件冒泡的效果,为了阻止事件冒泡----->
            1. window.event.cancelBubble = true;谷歌,IE8支持,火狐不支持
            window.event就是一个对象,是IE的标准
            2. e.stopPropagation();
            window.event 和 e 都是事件参数对象,一个是IE标准,一个是火狐标准
            事件参数e在IE8中的浏览器中是不存在的,此时用window.event来代替

            addEventLinstener中的第三的参数是用来控制事件阶段的
            事件阶段有三个
            1-----》事件捕获阶段
            2-----》事件目标阶段
            3-----》事件冒泡阶段
            一般默认用冒泡阶段,很少用捕获阶段

For the same elements in different registration events, pointing to the same event handler

    
<body>
    <input type="button" value="nice!" id='btn'>

    <script>
        var btn = document.getElementById('btn');
        btn.onclick = f1;
        btn.onmouseover = f1;
        btn.onmouseout = f1;

        function f1(e) {
            switch (e.type) {
                case 'click':
                    alert("nice!");
                    break;
                case 'mouseover':
                    this.style.backgroundColor = '#def';
                    break;
                case 'mouseout':
                    this.style.backgroundColor = '#fed';
                    break;
            }
        }
    </script>
</body>

Guess you like

Origin www.cnblogs.com/1020-jj/p/10959710.html