html事件处理程序:直接写在html标签中的事件处理程序
<div onclick="fun()"></div>
DOM0级事件处理程序(无兼容性问题)
document.getElementById('fdiv').onclick = fun; function fun() { alert(1) }
相当于给元素添加一个属性,重复添加会造成覆盖
清空事件:document.getElementById('fdiv').onclick = null;
3. DOM2级事件处理程序
可以重复添加事件
addEventListener removeEventListener
document.getElementById('fdiv').addEventListener('click', fun, false);
document.getElementById('fdiv').addEventListener('click', fun1, false);
document.getElementById('fdiv').removeEventListener('click', fun, false);
function fun() {
alert(1)
}
function fun() {
alert(2)
}
4. IE事件处理程序
可以重复添加事件
document.getElementById('fdiv').attachEvent('onclick', fun, false);
document.getElementById('fdiv').attachEvent('onclick', fun1, false);
document.getElementById('fdiv').detachEvent('onclick', fun, false);
function fun() {
alert(1)
}
function fun1() {
alert(2)
}
5.实现浏览器兼容
var eventUtil = {
addHander: function(element, type, hander){
if(window.addEventListener){
element.addEventListener(type, hander, false);
}else if(window.attachEvent){
element.attachEvent('on'+type, hander, false);
}else{
element['on'+type] = hander;
}
},
removeHander: function(element, type, hander){
if(window.addEventListener){
element.removeEventListener(type, hander, false);
}else if(window.attachEvent){
element.detach('on'+type, hander, false);
}else{
element['on'+type] = null;
}
},
getEvent: function(event){
return event?event:window.event;
},
getElement: function(event){
return event.target || event.srcElement;
},
preventDefault: function(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
},
stopPropagation: function(event){
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
}
}
};