码迷,mamicode.com
首页 > 编程语言 > 详细

Javascript 的addEventListener()及attachEvent()区别分析

时间:2015-06-09 11:33:37      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

原文地址:http://www.jb51.net/article/18220.htm
大家都知道事件的用法就是当某个事件(状况)被触发了之后就会去执行某个Function, 尤其是Javascript, 在当红AJAX的催化下, 了解Javascript的Event用法更加重要, 在这里就大概介绍一下avascript的Event用法.
 

Mozilla中:

addEventListener的使用方式:

target.addEventListener(type, listener, useCapture);

target: 文档节点、document、window 或 XMLHttpRequest。
type: 字符串,事件名称,不含“on”,比如“click”、“mouseover”、“keydown”等。
listener :实现了 EventListener 接口或者是 JavaScript 中的函数。
useCapture :是否使用捕捉,一般用 false 。例如: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);});

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

W3C格式:

removeEventListener(event,function,capture/bubble);

Windows IE的格式如下:

detachEvent(event,function);


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);
适应的浏览器版本不同,同时在使用的过程中要注意
attachEvent方法 按钮onclick IE中使用
addEventListener方法 按钮click fox中使用
两者使用的原理:可对执行的优先级不一样,下面实例讲解如下:
attachEvent方法,为某一事件附加其它的处理事件。(不支持Mozilla系列)
addEventListener方法 用于 Mozilla系列
举例: 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
如果是Mozilla系列,并不支持该方法,需要用到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
实例:(要注意的是div必须放到js前面才行)

复制代码 代码如下:

<html>
<head>
</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>

 

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

DOM1 协定:

 

Event Name

Description

onblur()

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

onchange0

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

onclick0

The mouse has been clicked on an element.

ondblclick()

The mouse has been double-clicked on an element.

onfocus()

The element has gotten focus.

onkeydown()

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

onkeypress()

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

onkeyup()

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

onload()

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

onmousedown()

A mouse button has been pressed.

onmousemove()

The mouse has been moved.

onmouseout()

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

onmouseover()

The mouse has moved over an element.

onmouseup()

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()

The form has been submitted.

onunload()

The document or frameset has been unloaded.


DOM2 的进化:

DOM 0 Event

DOM 2 Event

onblur()

blur

onfocus()

focus

onchange()

change

onmouseover()

mouseover

onmouseout()

mouseout

onmousemove()

mousemove

onmousedown()

mousedown

onmouseup()

mouseup

onclick()

click

ondblclick()

dblclick

onkeydown()

keydown

onkeyup()

keyup

onkeypress()

keypress

onsubmit()

submit

onload()

load

onunload()

unload

 新的DOM2 用法可以addEventListener()这个函数来观察到:

addEventListener(event,function,capture/bubble);

参数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的模式.这里用图像的Rollover例子来表现事件的用法:

<!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>

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

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

W3C格式:

removeEventListener(event,function,capture/bubble);

Windows IE的格式如下:

detachEvent(event,function);

数据参考: Chapter 14 - Browsers and JavaScript, JavaScript Step by Step, by Steve Suehring

Javascript 的addEventListener()及attachEvent()区别分析

标签:

原文地址:http://www.cnblogs.com/gobiggirl/p/4562835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!