js随笔之事件流

来源:互联网 发布:淘宝上主板可靠吗 编辑:程序博客网 时间:2024/05/21 11:20
多个彼此嵌套的元素拥有相同的事件,最内部的事件被触发后外边的同类型的事件也会被触发,多个元素同类型事件同时执行被称作事件流。其中事件流又分为冒泡与捕捉两种,可在addEventListener第三个参数设置true或false来决定事件流的类型。接下来上代码
<!DOCTYPE html><html>  <head>  <style type="text/css">    div {width: 200px; height: 200px; background-color: red;}    p {width: 200px; height: 100px; background-color: yellow;}    span { background-color: pink;}</style></head>  <body>  <div ><p><span>i am span</span></p></div></body><script type="text/javascript">    dv=document.getElementsByTagName("div")[0];    dv.addEventListener('click',f1);    p=document.getElementsByTagName("p")[0];    p.addEventListener('click',f2);    span=document.getElementsByTagName("span")[0];    span.addEventListener('click',f3);    function f1(){        console.log("this is div")    }    function f2(){        console.log("this is p")    }    function f3(){        console.log("this is span")    }</script>  </html>  

当单击span标签的时候,在控制台中会分别显示this is span、this is p、this is div,这种显示又叫冒泡类型,也就是由里到外的事件触发。与之相反的就是捕捉类型。当我们需要阻止事件流的发生,我们可以这么做

`
function f1(e){
console.log("this is div")
e.stopPropagation();
}
function f2(e){
console.log("this is p")
e.stopPropagation();
}
function f3(e){
console.log("this is span")
e.stopPropagation();
}

这样就能依次触发不同的事件。`

原创粉丝点击