阻止默认事件,阻止冒泡,阻止捕获
程序员文章站
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);
上一篇: 分享h5中alt和title的区别与用法