這篇文章主要是總結(jié)一些DOM事件的基礎(chǔ)知識點(diǎn)供置。
DOM事件的級別
DOM3是鼠標(biāo) 鍵盤這些事件
DOM事件模型
捕獲和冒泡
捕獲是從上到下 冒泡是從下到上
DOM事件流
分三個階段
點(diǎn)擊鼠標(biāo) -> 捕獲 -> 目標(biāo)階段 目標(biāo)對象 -> 冒泡
描述事件捕獲的具體流程
window -> document ->html標(biāo)簽 ->body-> ...->目標(biāo)元素
Event對象的常見應(yīng)用
event.preverntDefault() 阻止默認(rèn)行為
event.stopPropagation() 阻止冒泡事
event.stoplmmediatePropagation()
event.currentTarget 當(dāng)前綁定的事件的對象
event.target 觸發(fā)事件的目標(biāo)對象
自定義事件
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">
目標(biāo)元素
</div>
<script>
// 捕獲
var ev = document.getElementById('ev');
window.addEventListener('click', function () {
console.log('window captrue')
}, true) // false為箭頭捕獲 true為監(jiān)聽冒泡
document.addEventListener('click', function () {
console.log('document captrue')
}, true)
// html節(jié)點(diǎn)
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為監(jiān)聽冒泡
document.addEventListener('click', function () {
console.log('document bubbling')
}, false)
// html節(jié)點(diǎn)
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')
})
// 觸發(fā)自定義事件
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>