添加事件處理器
function buttonAlert(){
alert("You clicked the button");
}
document.getElementById("myButton").onclick = buttonAlert;
在注冊(cè)事件處理器時(shí)恩敌,函數(shù)名后面不能有括號(hào)。
刪除事件處理器
要?jiǎng)h除事件處理器乔外,只需要簡(jiǎn)單地給它賦值null:
document.getElementById("myButton").onclick = null;
event對(duì)象
跨瀏覽器的事件處理器
MyElement.onclick = function(e){
if (!e) var e = window.event;
//這樣e就能代表任何瀏覽器的event對(duì)象
}
為了實(shí)現(xiàn)跨瀏覽器的代碼床三,我們需要在腳本中檢測(cè)event對(duì)象是否具有我們需要的方法和屬性:
if (!e) var e = window.event;
var element = (e.target) ? e.target : e : e.srcElement;
W3C方式
W3C提供了addEventListener和removeEventListener方法
element.addEventListener("click", myFunction, falise);
element.removeEventListener("click", myOtherFunction, false);
第一個(gè)參數(shù)指明要捕獲的事件,第二個(gè)參數(shù)指明時(shí)間要執(zhí)行的函數(shù)杨幼。
微軟方式
微軟提供了兩種類(lèi)似的方法:attachEvent和detachEvent
element.attachEvent("onclick", myFunction);
element.detachEvent("onclick", myFunction);
跨瀏覽器的實(shí)現(xiàn)方式
function addEventHandler(element, eventType, handlerFunction) {
if (element.addEventListener) {
element.addEventListener (eventType, handlerFunction);
} else if (element.attachEvent) {
element.attachEvent ("on" + eventType, handlerFunction);
}
}
鼠標(biāo)點(diǎn)擊
在W3C瀏覽器里撇簿,鼠標(biāo)左鍵返回0,中鍵返回1差购,右鍵返回2四瘫。
在微軟瀏覽器里,鼠標(biāo)左鍵返回1欲逃,右鍵返回2找蜜,中鍵返回4。
document.onkeydown = function(e) {
if (!e) var e = window.event;
alert(e.keyCode + " is the code for " + String.fromCharCode(e.keyCode));
}