javascript考点 —— DOM事件

一、基本概念:DOM事件级别

DOM0    element.onclick = function(){}

DOM2    element.addEventListener('click',function(){},false)

DOM3    element.addEventListener('keyup',function(){},false)

二、DOM事件模型

捕获和冒泡,捕获是自上而下,冒泡是自下而上。

三、DOM事件流

浏览器在为当前这个页面在与用户交互的过程中,比如点击鼠标左键,这个事件是怎么传到页面上的。一个完整的时间流分三个部分:捕获、目标阶段。也就是说事件通过捕获到达目标元素,目标元素在上传到window对象。

四、描述DOM事件捕获的具体流程

冒泡流程就是捕获流程倒回去。

下面是一个捕获流程的例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>evet</title>
</head>
<body>
    <div id="ev">
        <style>
            #ev{
                width: 300px;
                height:100px;
                background: red;
                color:#fff;
                text-align:center;
                line-height: 100px;
            }
        </style>
        目标元素
    </div>
    <script>
        var ev=document.getElementById('ev');
        window.addEventListener('click',function(){
            console.log('window captrue');
        },true)
        document.addEventListener('click',function(){
            console.log('document captrue')
        },true)
        document.addEventListener('click',function(){
            console.log('html captrue')
        },true)
        document.body.addEventListener('click',function(){
            console.log('body captrue')
        },true)
        ev.addEventListener('click',function(){
            console.log('ev captrue')
        },true)
    </script>
</body>
</html>

输出结果是:

将上面的addEventListener的true改为false就是事件冒泡的过程。

五、Event对象的常见应用

event.preventDefault()       //阻止默认事件
event.stopPropagation()      //阻止冒泡事件
evevt.stopImmediatePropagation()       //事件分发
event.currentTarget     //当前所绑定的事件
event.target         //获取当前触发事件的元素

六、自定义事件

var eve = new Event('custome')
ev.addEventListener('custome',function(){
    console.log('custome');
});
ev.dispatchEvent(eve);

//CustomEvent也是自定义事件的函数,它除了指定事件名,后面还可以跟一个object作为参数,传入数据

自定义事件例子,这是自动触发的:

        var eve = new Event('test')
        ev.addEventListener('test',function(){
            console.log('test')
        })
        ev.dispatchEvent(eve)

猜你喜欢

转载自blog.csdn.net/zhanghuali0210/article/details/82379843