事件綁定
dom0
element.onclick = function(){};
element.onclick = 函數(shù)名;
element.onclick = function(){
函數(shù)名(參數(shù));
}
element.onclick = "";
dom2級
element.addEventListener('click',function(){},false);
element.addEventListener('click',函數(shù)名,false);
element.addEventListener('click',a=function(){
函數(shù)名(參數(shù));
},false);
element.removeEventListener('click',函數(shù)名);
element.removeElentListener('click',a);
element.attachEvent('onclick',function(){});
element.attachEvent('onclick',函數(shù)名);
element.attachEvent('onclick',function(){
函數(shù)名(參數(shù))
});
element.detachEvent('onclick',函數(shù)名);
dom2級事件兼容性解決
function addEvent(type,handle,element){
if(element.addEventListener){
element.addEventListener(type,handle,false);
}else{
element.attachEvent("on"+type,handle);
}
}
function removeEvent(type,handle,elemnt){
if(element.removeEventListener){
element.removeElementListener(type,handle);
}else{
element.detachEvent(type,handle);
}
}
事件對象 event
function 函數(shù)名(event){
var event = evnet || window.event;
}
element.onclick = function(event){
函數(shù)名(event);
}
阻止冒泡
event.stopPropagation(); w3c
event.cancelBubble = true; ie8
function stopPropagation(event){
if(event.stopPropagation){
event.stopPropagation()
}else{
event.cacelBubble = true;
}
}
瀏覽器默認(rèn)行為
event.preventDefault(); w3c
event.returnValue = false; IE8
function stopDefault(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
}
通過dom2級事件移除事件,必須是定義好的函數(shù)惰瓜,或者在使用時寫 a = function(){}