欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

阻止默认事件,阻止冒泡,阻止捕获

程序员文章站 2022-05-13 16:03:13
...

一、阻止默认事件:
event.preventDefault();

let aEle = document.getElementsByTagName("a")[0];
aEle.addEventListener("click", e => {
    let event = e || window.event;
    //阻止默认事件
    event.preventDefault();
    if (event.target.localName == "a") {
        event.target.nextElementSibling.style.color = "red";
    }
})

二、阻止冒泡

event.stopPropagation();

p1Ele.addEventListener(`click`,e=> {
    let event=e||window.event
    console.log(`p`);
    p1Ele.style.backgroundColor=`yellow`;
    event.stopPropagation();
    
});	

三、阻止捕获

event.stopImmediatePropagation();

artEle.addEventListener(`click`,e=> {
    let event=e||window.event;
    console.log(`article`);
    artEle.style.backgroundColor=`orange`;
    event.stopImmediatePropagation();
},true);