[html]事件处理addEventListener详解

来源:互联网 发布:redis和mysql的结合 编辑:程序博客网 时间:2024/06/05 20:55
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>事件处理addEventListener详解</title>    <style>    .div1 {        background-color: rgba(0, 0, 0, .3);        width: 400px;        height: 400px;    }        .div2 {        background-color: rgba(0, 0, 0, .4);        width: 300px;        height: 300px;    }        .div3 {        background-color: rgba(0, 0, 0, .5);        width: 200px;        height: 200px;    }    </style>    <script>    function initapp() {        var el1 = document.getElementById('div1');        var el2 = document.getElementById('div2');        var el3 = document.getElementById('div3');        var useCapture = false;        // 是否使用捕获:true-使用捕获,false-使用冒泡(目前普遍使用的方式)        // 使用捕获:从根节点开始自上而下,检测每个节点是否注册了事件监听器。如果注册了并且 useCapture为true,则执行。        // 使用冒泡:从目标节点自下而上到根节点,检测每个节点是否注册了事件监听器。如果注册了并且 useCapture为false,则执行。        // 自上而下路径:Window->document->html->body->xxx        // useCapture = false; 点击div3时控制台打印:DIV#div3 DIV#div2 DIV#div1 HTML#        // useCapture = true;  点击div3时控制台打印:HTML# DIV#div1 DIV#div2 DIV#div3        el1.addEventListener('click', myclick, useCapture);        el2.addEventListener('click', myclick, useCapture);        el3.addEventListener('click', myclick, useCapture);        document.getElementsByTagName('html')[0].addEventListener('click', myclick, useCapture);        //window.addEventListener('click', myclick, useCapture);    }    function myclick(event) {        //event 触发的点击事件        //this 当前节点        console.log(this.tagName + "#" + this.id);        //event.preventDefault();        //event.stopPropagation();//阻止传播,若useCapture=false为阻止向上冒泡,否则为阻止向下传播    }    </script></head><body onload="initapp()">    <div id="div1" class="div1">div1        <div id="div2" class="div2">div2            <div id="div3" class="div3">div3</div>        </div>    </div></body></html>

0 0
原创粉丝点击