这篇文章主要是总结一些DOM事件的基础知识点。
DOM事件的级别

DOM3是鼠标 键盘这些事件
DOM事件模型
捕获和冒泡
捕获是从上到下 冒泡是从下到上
DOM事件流
分三个阶段
点击鼠标 -> 捕获 -> 目标阶段 目标对象 -> 冒泡
描述事件捕获的具体流程
window -> document ->html标签 ->body-> ...->目标元素
Event对象的常见应用
event.preverntDefault() 阻止默认行为
event.stopPropagation() 阻止冒泡事
event.stoplmmediatePropagation()
event.currentTarget 当前绑定的事件的对象
event.target 触发事件的目标对象
自定义事件
var eve = new Event('custome');
var ev = document.getElementById('div');
ev.addEventListener('custome',function(){
console.log('custome')
})
ev.dispatchEvent(eve)
一些测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
#ev {
width: 300px;
height: 100px;
background: red;
color: #fff;
text-align: center;
line-height: 100px;
}
</style>
<title>DOM事件代码示例</title>
</head>
<body>
<div id="ev">
目标元素
</div>
<script>
// 捕获
var ev = document.getElementById('ev');
window.addEventListener('click', function () {
console.log('window captrue')
}, true) // false为箭头捕获 true为监听冒泡
document.addEventListener('click', function () {
console.log('document captrue')
}, true)
// html节点
document.documentElement.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)
// 冒泡
var ev = document.getElementById('ev');
window.addEventListener('click', function () {
console.log('window bubbling')
}, false) // false为箭头捕获 true为监听冒泡
document.addEventListener('click', function () {
console.log('document bubbling')
}, false)
// html节点
document.documentElement.addEventListener('click', function () {
console.log('html bubbling')
}, false)
document.body.addEventListener('click', function () {
console.log('body bubbling')
}, false)
ev.addEventListener('click', function () {
console.log('ev bubbling')
}, false)
// 自定义事件
var eve = new Event('test');
ev.addEventListener('test', function () {
console.log('test dispatch')
})
// 触发自定义事件
ev.dispatchEvent(eve);
var eve1 = new CustomEvent('test1', {
detail: {
username: "davidwalsh"
},
bubbles: true,
cancelable: false
})
ev.addEventListener('test1',function(e){
console.log(e);
})
ev.dispatchEvent(eve1)
</script>
</body>
</html>
网友评论