全回顾扫盲js之DOM事件流

dom事件流分为捕获流和冒泡流

冒泡是从dom向外走,div->body->html->document->window,捕获相反,window.addEventListener('click', function(){}, false),最后的布尔值确定是冒泡还是捕获。true是捕获,false是冒泡

window.addEventListener('click', function () {
    console.log('window clicked')
}, true)
document.addEventListener('click', function () {
    console.log('document clicked')
}, true)
document.documentElement.addEventListener('click', function () {
    console.log('html clicked')
}, true)
document.body.addEventListener('click', function () {
    console.log('body clicked')
}, true)
document.getElementById('container').addEventListener('click', function () {
    console.log('container clicked')
}, true)

阻止冒泡可以用e.stopPropagation()

document.getElementById('container').onclick = function (e) {
    console.log(111)
    e.stopPropagation()
}
window.addEventListener('click', function () {
    console.log('window clicked')
}, false)
document.addEventListener('click', function () {
    console.log('document clicked')
}, false)
document.documentElement.addEventListener('click', function () {
    console.log('html clicked')
}, false)
document.body.addEventListener('click', function () {
    console.log('body clicked')
}, false)
document.getElementById('container').addEventListener('click', function () {
    console.log('container clicked')
}, false)

完整的dom事件传导经历三个阶段 : 捕获-》目标-》冒泡

document.getElementById('container').onclick = function (e) {
    console.log(111)
}
window.addEventListener('click', function () {
    console.log('window 冒泡')
}, false)
document.addEventListener('click', function () {
    console.log('document 冒泡')
}, false)
document.documentElement.addEventListener('click', function () {
    console.log('html 冒泡')
}, false)
document.body.addEventListener('click', function () {
    console.log('body 冒泡')
}, false)
document.getElementById('container').addEventListener('click', function () {
    console.log('container 冒泡')
}, false)

window.addEventListener('click', function () {
    console.log('window 捕获')
}, true)
document.addEventListener('click', function () {
    console.log('document 捕获')
}, true)
document.documentElement.addEventListener('click', function () {
    console.log('html 捕获')
}, true)
document.body.addEventListener('click', function () {
    console.log('body 捕获')
}, true)
document.getElementById('container').addEventListener('click', function () {
    console.log('container 捕获')
}, true)

随机浏览