• 七十二:JavaScript之JS事件之event对象属性与方法


    1.type:事件类型

    根据事件类型,执行不同的js代码

    <body>
    <button id="btn">点击按钮</button>
    <script>
    var btn = document.getElementById('btn');
    var func = function (event){
    console.log(event.type == 'click' ? '点击事件被触发了': event.type == 'mouseout' ? '鼠标移除事件被触发了': '未知事件')
    };
    btn.addEventListener('click', func);
    btn.addEventListener('mouseout', func);
    </script>
    </body>

    2.target和currentTarget

    target:事件源,点击的哪个元素,target就是哪个元素

    currentTarget:事件执行的元素,事件绑定在哪个元素上面,就指向哪个元素

    <div id="parent">
    <div id="child">点击子元素</div>
    </div>
    <script>
    var parent = document.getElementById('parent');
    parent.addEventListener('click', function (event){
    console.log('event.target: ', event.target);
    console.log('event.currentTarget: ', event.currentTarget);
    });
    </script>

    3.preventDefault:阻止默认行为

    4.stopPropagation:阻止事件冒泡或者捕获

    <div id="parent">
    <div id="child">点击子元素</div>
    </div>
    <script>
    var parent = document.getElementById('parent');
    var child = document.getElementById('child');
    parent.addEventListener('click', function (event){console.log('parent');});
    child.addEventListener('click', function (event){
    console.log('child');
    event.stopPropagation(); // 阻止冒泡,不再执行父元素的事件
    });
    </script>

    5.client、page、screen

    clientY:指浏览器顶部底边到点击时鼠标的位置,不包含滚动轴的距离

    pageY:指浏览器顶部底边到点击时鼠标的位置,包含滚动轴的距离

    screenY:指屏幕顶部底边到点击时鼠标的位置(不会根据浏览器窗口缩放改变)

    X轴与Y轴同理可获得

        <style>
    #box{height: 1000px; background: limegreen;}
    </style>
    </head>
    <body>
    <div id="box"></div>
    <script>
    var box = document.getElementById('box');
    box.addEventListener('click', function (event){
    console.log(`clientY:${event.clientY};pageY:${event.pageY};screenY:${event.screenY};`)
    });
    </script>
    讨论群:249728408
  • 相关阅读:
    ios存储 plist 偏好设置 自定义对象存储
    Spring中Bean的生命中期与InitializingBean和DisposableBean接口
    Spring中BeanPostProcessor
    cxf
    ios快捷键
    UIPickerView
    ios通知-kvo
    7.python 装饰器
    5.python内置函数
    4.python 深拷贝 浅拷贝 函数 匿名函数lambda
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/14193622.html
Copyright © 2020-2023  润新知