dom事件

一、dom事件级别

dom0: ele.onclick=function(){}
dom1: 指定时没有涉及事件相关的内容
dom2: ele.addEventListener("click",function(){},false) 后一个参数指定是冒泡还是捕获。
dom3:ele.addEventListener("keyup",function(){},false) 增加了很多事件类型,如鼠标事件,键盘事件等等。

二、dom事件模型
捕获(从上往下)和冒泡(从下往上),默认为冒泡事件。
捕获:

<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
    <div id="ev">
    <style>
    #ev{
        width:200px;
        height: 100px;
        text-align:center;
        background:red;
        line-height:100px;
        color:#fff;
    }
    </style>
    js事件
    </div>
</body>
<script>
let ev=document.getElementById("ev");
ev.addEventListener('click',function () {
    console.log("ev capture");
},true);
window.addEventListener('click',function () {
    console.log("window capture");
},true);
document.addEventListener('click',function () {
    console.log("document capture");
},true);
document.documentElement.addEventListener('click',function () {
    console.log("html capture");
},true);
document.body.addEventListener('click',function () {
    console.log("body capture");
},true);
</script>
</html>

window-document-html(document.documentElement)-body-html结构一层一层的传递,最后到达目标元素,依次打印为window capture、document capture、html capture、body capture、ev capture。
冒犯过程相反,若需要演示把上面代码监听函数中传入参数改为false就行了,默认为false。
三、事件流
浏览器与用户交互的过程
在这里插入图片描述
四、event对象
event.preventDefault() :阻止默认事件,比如a连接,添加点击事件后阻止默认事件就是阻止了a连接跳转行为。
event.stopProgapation() :阻止冒泡行为,比如父元素绑定一个事件,子元素绑定一个事件,如果不阻止冒泡,子元素事件触发的时候父元素的事件也会被触发。
event.stopImmediatePropagation() :当一个元素绑定多个事件时,一个事件的触发会导致全部事件触发。event.stopImmediatePropagation() 可以阻止这一状况。
event.currentTarget 当前绑定的事件的对象。
event.target 当前触发事件的元素。
五、自定义事件

let eve= new Event("test");
ev.addEventListener('test',function(){
    console.log("test dispatch");
});
ev.dispatchEvent(eve);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值