天天看點

HTML addEventListener() 方法和attachEvent()差別分析

文法

element.addEventListener(event,function,useCapture)

參數值

參數 描述
event

必須。字元串,指定事件名。

注意: 不要使用 "on" 字首。 例如,使用 "click" ,而不是使用 "onclick"。

提示: 所有 HTML DOM 事件,可以檢視我們完整的 HTML DOM Event 對象參考手冊。

function

必須。指定要事件觸發時執行的函數。

當事件對象會作為第一個參數傳入函數。 事件對象的類型取決于特定的事件。例如, "click" 事件屬于 MouseEvent(滑鼠事件) 對象。

useCapture

可選。布爾值,指定事件是否在捕獲或冒泡階段執行。

可能值:

  • true - 事件句柄在捕獲階段執行
  • false- false- 預設。事件句柄在冒泡階段執行

執行個體

您可以通過函數名來引用外部函數。

該執行個體示範了在使用者點選a <button> 元素時如何執行函數:

<span style="font-family:SimSun;"><span style="font-size:18px;">document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}</span></span>
           

您可以在文檔中添加許多事件,添加的事件不會覆寫已存在的事件。

該執行個體示範了如何在<button>元素中添加兩個點選事件:

<span style="font-family:SimSun;"><span style="font-size:18px;">document.getElementById("myBtn").addEventListener("click", myFunction);
document.getElementById("myBtn").addEventListener("click", someOtherFunction);</span></span>
           

您可以在同一個元素中添加不同類型的事件。

該執行個體示範了如何在同一個 <button> 元素中添加多個事件:

<span style="font-family:SimSun;"><span style="font-size:18px;">document.getElementById("myBtn").addEventListener("mouseover", myFunction);
document.getElementById("myBtn").addEventListener("click", someOtherFunction);
document.getElementById("myBtn").addEventListener("mouseout", someOtherFunction);</span></span>
           

修改 <button> 元素的背景:

<span style="font-family:SimSun;"><span style="font-size:18px;">document.getElementById("myBtn").addEventListener("click", function(){
    this.style.backgroundColor = "red";
});</span></span>
           

使用 removeEventListener() 方法移除由 addEventListener() 方法添加的事件句柄:

// 添加 <div> 事件句柄

<span style="font-family:SimSun;"><span style="font-size:18px;">document.getElementById("myDIV").addEventListener("mousemove", myFunction);</span></span>
           

// 移除 <div> 事件句柄

<span style="font-family:SimSun;"><span style="font-size:18px;">document.getElementById("myDIV").removeEventListener("mousemove", myFunction);</span></span>
           

如果浏覽器不支援 addEventListener() 方法, 你可以使用 attachEvent() 方法替代。

以下執行個體示範了跨浏覽器的解決方法:

<span style="font-family:SimSun;"><span style="font-size:18px;">var x = document.getElementById("myBtn");
if (x.addEventListener) {                    //所有主流浏覽器,除了 IE 8 及更早 IE版本
    x.addEventListener("click", myFunction);
} else if (x.attachEvent) {                  // IE 8 及更早 IE 版本
    x.attachEvent("onclick", myFunction);
}</span></span>
           

 addEventListener() 方和attachEvent()差別

addEventListener(event,function,capture/bubble);

參數event如上表所示, 

function是要執行的函數, 

capture與bubble分别是W3C制定得兩種時間模式,

簡單來說capture就是從document的開始讀到最後一行, 再執行事件, 

而bubble則是先尋找指定的位置再執行事件.

capture/bubble的參數是布爾值, True表示用capture, False則是bubble.

Windows Internet Explorer( IE )也有制定一種EventHandler, 是 attachEvent(), 格式如下:

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

比較特别的是attachEvent不需要指定capture/bubble的參數, 因為在windows IE環境下都是使用Bubble的模式.

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格式:

removeEventListener(event,function,capture/bubble);

Windows IE的格式如下:

detachEvent(event,function);

事件觸發時,會将一個 Event 對象傳遞給事件處理程式,比如:

document.getElementById("testText").addEventListener("keydown", function (event) { alert(event.keyCode); }, false);

适應的浏覽器版本不同,同時在使用的過程中要注意

(1)attachEvent方法 按鈕onclick IE中使用

(2)addEventListener方法 按鈕click fox中使用 

兩者使用的原理:可對執行的優先級不一樣,下面執行個體講解如下: 

(1)attachEvent方法,為某一事件附加其它的處理事件。(不支援Mozilla系列)

(2)addEventListener方法 用于 Mozilla系列

舉例:

<span style="font-family:SimSun;">document.getElementById("btn").onclick = method1; 
document.getElementById("btn").onclick = method2; 
document.getElementById("btn").onclick = method3;</span>
           

如果這樣寫,那麼将會隻有medhot3被執行

寫成這樣:

<span style="font-family:SimSun;">var btn1Obj = document.getElementById("btn1"); //object.attachEvent(event,function); 
btn1Obj.attachEvent("onclick",method1); 
btn1Obj.attachEvent("onclick",method2); 
btn1Obj.attachEvent("onclick",method3);</span>
           

執行順序為method3->method2->method1

如果是Mozilla系列,并不支援attachEvent該方法,需要用到

<span style="font-family:SimSun;">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);</span>
           

執行順序為method1->method2->method3

執行個體:(要注意的是div必須放到js前面才行) 

<span style="font-family:SimSun;"><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> </span>
           

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

參考:http://www.runoob.com/jsref/met-element-addeventlistener.html

           http://www.jb51.net/article/18220.htm

繼續閱讀