Javascript 的addEventListener()及attachEvent()區別分析

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.