zoukankan      html  css  js  c++  java
  • addEventListener

    element.addEventListener(event, function, useCapture)

    event:指定事件名

    function:指定事件触发时执行的函数。

    useCapture:布尔值,指定事件在捕获或冒泡阶段执行。true:事件在捕获阶段执行,false:事件在冒泡阶段执行。

    例子:

    html代码:

       <div id="parent"> 
            <div id="child">
            </div>
        </div>

    css代码:

      #parent{
            width: 400px;
            height: 120px;
            background-color: green;
            margin: 50px;
        }
        #child{
            width: 100px;
            height: 120px;
            background-color: orange;
            margin-left: 80px;
            cursor: pointer;
        }

    效果图:

    js代码:

         var child = document.getElementById('child');
            var parent = document.getElementById('parent');
    
            parent.addEventListener('click',function(){
                console.log(1);
            },true);
            parent.addEventListener('click',function(){
                console.log(2);
            },false);
            child.addEventListener('click',function(){
                console.log(3);
            },true);
            child.addEventListener('click',function(){
                console.log(4);
            },true);

    点击child元素后,打印结果为:1 3 4 2

    分析:点击事件后,事件从元素向目标元素传递(捕获阶段),然后到目标元素(目标阶段),最后从目标元素向根元素传递。在捕获阶段中,输出1,在目标阶段输出3,4,在冒泡阶段输出2。

  • 相关阅读:
    5402.绝对差不超过限制的最长数组
    快乐数
    无重复字符的最长子串
    数组中数字出现的次数
    盛最多的水
    对角线遍历
    LeetCode第24场周赛
    CSS样式
    笔记
    开关电源设计
  • 原文地址:https://www.cnblogs.com/fe-huahai/p/5727551.html
Copyright © 2011-2022 走看看