事件绑定
dom0
element.onclick = function(){};
element.onclick = 函数名;
element.onclick = function(){
函数名(参数);
}
element.onclick = "";
dom2级
element.addEventListener('click',function(){},false);
element.addEventListener('click',函数名,false);
element.addEventListener('click',a=function(){
函数名(参数);
},false);
element.removeEventListener('click',函数名);
element.removeElentListener('click',a);
element.attachEvent('onclick',function(){});
element.attachEvent('onclick',函数名);
element.attachEvent('onclick',function(){
函数名(参数)
});
element.detachEvent('onclick',函数名);
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 函数名(event){
var event = evnet || window.event;
}
element.onclick = function(event){
函数名(event);
}
阻止冒泡
event.stopPropagation(); w3c
event.cancelBubble = true; ie8
function stopPropagation(event){
if(event.stopPropagation){
event.stopPropagation()
}else{
event.cacelBubble = true;
}
}
浏览器默认行为
event.preventDefault(); w3c
event.returnValue = false; IE8
function stopDefault(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
}
通过dom2级事件移除事件,必须是定义好的函数,或者在使用时写 a = function(){}
网友评论