您现在的位置:首页 >> 前端 >> 内容

addEventListener(主流)和attachEvent(IE678)介绍

时间:2017/12/14 13:46:33 点击:

  核心提示:1、addEventListener()主流浏览器addEventListener() 方法用于向指定元素添加事件句柄,使用 removeEventListener() 方法来移除 addEventL...

1、addEventListener()主流浏览器

addEventListener() 方法用于向指定元素添加事件句柄,使用 removeEventListener() 方法来移除 addEventListener() 方法添加的事件句柄。

element.addEventListener(event, function, useCapture),event为事件名不要使用on。

使用addEventListener()添加多个事件时不会发生覆盖。

var element=document.getElementById("id");  
element.onclick=function(){  
    alert(1);  
}  
element.onclick=function(){  
    alert(2);  
}  

如上会发生覆盖,不会发生alert(1)。

2、element.addEventListener(event, function, useCapture)

1、useCapture捕获形式,默认false事件句柄在冒泡阶段执行,true事件句柄在捕获阶段执行。

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="utf-8">  
    <title>addEventListener</title>  
</head>  
<style type="text/css">  
*{margin: 0;padding: 0;}  
#parent{  
        background-color: red;width: 200px;height: 200px;overflow: hidden;  
    }  
#child{  
        background-color: black;width: 100px;height: 100px;margin: 50px;  
    }  
</style>  
<body>  
<p id="parent">  
    <p id="child"></p>  
</p>  
<script type="text/javascript">  
document.getElementById("parent").addEventListener("click",function(e){  
                alert("parent事件被触发,"+this.id);  
            },false)  
document.getElementById("child").addEventListener("click",function(e){  
                alert("child事件被触发,"+this.id)  
            },false)  
  
</script>  
</body>  
</html>  

addEventListener(主流)和attachEvent(IE678)介绍

如上,如果点击child(black),则先alert child然后alert parent。但是如果只点击红色时,则只会alert parent。

如果将useCapture改为true,那么点击黑色时则先alert parent然后alert child。但是如果只点击红色时,则只会alert parent。

3、 target.attachEvent(eventNameWithOn, function)(IE6-8)

事件名伴随On(eventNameWithOn)监听的事件名以on前置,类似一个属性的管理者,譬如当你使用onclick时能够监听你的click事件。element.attachEvent("onclick", function);

Tags:AD DD DE EV 
作者:网络 来源:zgjxyszh的博