[No00006A]Js的addEventListener()及attachEvent()区别分析【js中的事件监听】

时间:2021-02-05 08:55:57

1.添加时间监听:

Chrom中:
addEventListener的使用方式:

target.addEventListener(type, listener, useCapture); 

target: 文档节点、document、window 或 XMLHttpRequest。

type: 字符串,事件名称,不含"on",比如"click"、"mouseover"、"keydown"等。

listener :实现了 EventListener 接口或者是 JavaScript 中的函数。

useCapture :是否使用捕捉,看了后面的事件流一节后就明白了,一般用 false  。

事件触发时,会将一个 Event 对象传递给事件处理程序,比如: document.getElementById("testText").addEventListener("keydown", function (event) { alert(event.keyCode); }, false);

IE中:

target.attachEvent(type, listener); 

target: 文档节点、document、window 或 XMLHttpRequest。
type: 字符串,事件名称,含"on",比如"onclick"、"onmouseover"、"onkeydown"等。
listener :实现了 EventListener 接口或者是 JavaScript 中的函数。 例如:document.getElementById("txt").attachEvent("onclick",function(event){alert(event.keyCode);});

两者使用的原理:可对执行的优先级不一样,下面实例讲解如下: 
a.attachEvent方法,为某一事件附加其它的处理事件。(不支持Chrome系列)

document.getElementById("btn").onclick = method1;
document.getElementById("btn").onclick = method2;
document.getElementById("btn").onclick = method3;//如果这样写,那么将会只有medhot3被执行

如果写成这样:

var btn1Obj = document.getElementById("btn1"); //object.attachEvent(event,function);
btn1Obj.attachEvent("onclick",method1);
btn1Obj.attachEvent("onclick",method2);
btn1Obj.attachEvent("onclick",method3);//执行顺序为method3->method2->method1

b.addEventListener方法 用于 Chrome系列 
如果是Chrome系列,并不支持该方法,需要用到addEventListener

var btn1Obj = document.getElementById("btn1");
//element.addEventListener(type,listener,useCapture);
btn1Obj.addEventListener("click",method1,false);
btn1Obj.addEventListener("click",method2,false);
btn1Obj.addEventListener("click",method3,false);//执行顺序为method1->method2->method3

所以要兼容Chrome和IE,要写if判断,举例:(要注意的是div必须放到js前面才行,文件编码为utf-8)

<html>

    <head>
<meta charset="utf-8">
</head> <body>
<div id="name1" style="border:1px solid red;padding:10px 10px 10px 10px;"
style="border:1px solid red;padding:10px 10px 10px 10px;">
<div id="name2" style="border:1px solid green;padding:10px 10px 10px 10px;"
style="border:1px solid green;padding:10px 10px 10px 10px;">
点击
</div>
</div>
<div id="info">
</div>
<script type="text/javascript">
var name1 = document.getElementById('name1'); //要注意
var name2 = document.getElementById('name2'); //要注意
var info = document.getElementById('info');
if (name1.attachEvent) { //对于attachEvent前面的target我们一定要保证不为空
name1.attachEvent('onclick',
function() {
info.innerHTML += "红色" + "<br>";
});
name2.attachEvent('onclick',
function() {
info.innerHTML += "绿色" + "<br>";
});
} else {
name1.addEventListener('click',
function() {
info.innerHTML += "红色" + "<br>";
},
false);
name2.addEventListener('click',
function() {
info.innerHTML += "绿色" + "<br>";
},
false);
}
</script>
</body> </html>

那为什么会有含"on"和不含"on"的问题?

答案要从W3C的发展时间轴来看, DOM(Document Object Model)的模型可以分为两种, DOM 0 及 DOM 2. 从数字来看就可以知道DOM 0 当然是比较旧的协议, 我们直接来看DOM2 :

DOM 0&DOM1 协定 Event(Event Name)

DOM 2 Event

Description

onblur()

blur

The element has lost focus (that is, it is not selected by the user).

onchange()

change

The element has either changed (such as by typing into a text field) or the element has lost focus.

onclick()

click

The mouse has been clicked on an element.

ondblclick()

dblclick

The mouse has been double-clicked on an element.

onfocus()

focus

The element has gotten focus.

onkeydown()

keydown

A keyboard key has been pressed down (as opposed to released) while the element has focus.

onkeypress()

keypress

A keyboard key has been pressed while the element has focus.

onkeyup()

keyup

A keyboard key has been released while the element has focus.

onload()

load

The element has loaded (document, frameset, or image).

onmousedown()

mousedown

A mouse button has been pressed.

onmousemove()

mousemove

The mouse has been moved.

onmouseout()

mouseout

The mouse has been moved off of or away from an element.

onmouseover()

mouseover

The mouse has moved over an element.

onmouseup()

mouseup

A mouse button has been released.

onreset()

 

The form element has been reset, such as when a form reset button is pressed.

onresize()

 

The window's size has been changed.

onselect()

 

The text of a form element has been selected.

onsubmit()

submit

The form has been submitted.

onunload()

unload

The document or frameset has been unloaded.

addEventListener()这个函数只支持新的DOM2 :addEventListener(event,function,capture/bubble);

参数event如上表(DOM 2 Event)所示, function是要执行的函数, capture与bubble分别是W3C制定得两种时间模式,简单来说capture就是从document的开始读到最后一行, 再执行事件, 而bubble则是先寻找指定的位置再执行事件.
capture/bubble的参数是布尔值, True表示用capture, False则是bubble.

Windows Internet Explorer对应的EventHandler, 是 attachEvent(), 格式如下:

window.attachEvent("submit",myFunction());

比较特别的是attachEvent不需要指定capture/bubble的参数, 因为在windows IE环境下都是使用Bubble的模式.这里用个例子来表现事件的用法:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
Rollover
</title>
<script type="text/javascript">
function moveOver(imgObj) {
if (typeof window.addEventListener != "undefined") {
imgObj.addEventListener("mouseover",
function() {
imgObj.src = imgObj.id + "_over.png";
},
false);
imgObj.addEventListener("mouseout",
function() {
imgObj.src = imgObj.id + "_default.png";
},
false);
} else {
imgObj.attachEvent("onmouseover",
function() {
imgObj.src = imgObj.id + "_over.png";
});
imgObj.attachEvent("onmouseout",
function() {
imgObj.src = imgObj.id + "_default.png";
});
}
}
function rollover() {
var images = document.getElementsByTagName("img");
var roll = new RegExp("rollover");
var preload = [];
for (var i = 0; i < images.length; i++) {
if (images[i].id.match(roll)) {
preload[i] = new Image();
preload[i].src = images[i].id + "_over.png";
moveOver(images[i]);
}
}
}
if (typeof window.addEventListener != "undefined") {
window.addEventListener("load", rollover, false);
} else {
window.attachEvent("onload", rollover)
}
</script>
</head> <body>
<p>
<img id="rollover_home" name="img_home" src="rollover_home_default.png"
alt="Home">
</p>
<p>
<img id="rollover_about" name="img_about" src="rollover_about_default.png"
alt="About">
</p>
<p>
<img id="rollover_blog" name="img_blog" src="rollover_blog_default.png"
alt="Blog">
</p>
<p>
<img id="logo" name="img_logo" src="logo.png" alt="Braingia Logo">
</p>
</body>
</html>

ps:你需要图片素材下载:[No00006A]图片素材.7z

上述的 typeof window.addEventListener != "undefined" 程序代码可以判断使用者的浏览器是否支持AddEventListener这个事件模型, 如果不支持就使用attachEvent.

2.移除事件监听:

W3C 及 IE 同时支持移除指定的事件, 用途是移除设定的事件, 格式分别如下:

W3C格式:

removeEventListener(event,function,capture/bubble); 

Windows IE的格式如下:

detachEvent(event,function);