addEventListener(主流)和attachEvent(IE678)

来源:互联网 发布:网络语言 英文 编辑:程序博客网 时间:2024/06/05 13:35

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><div id="parent"><div id="child"></div></div><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>

如上,如果点击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);

IE6-8只支持冒泡。




原创粉丝点击