DOM0级事件处理程序
- 用onclick添加事件
btn.onclick = function(){
exmple.style.color = "#2C3E50";
exmple.style.background = "red";
alert(this.id)
}
DOM1级事件处理程序
- 用addEventListener 接收三个参数(“要处理的事件名”, 作为事件处理的函数, 一个布尔值布尔值true表示在捕获阶段调用事件处理程序,false反之。)添加事件.
document.addEventListener("click", function(){
exmple.style.color ="#42B983";
exmple.style.opacity =".4";
}, false)
document.addEventListener("DOMContentLoaded", function(){
exmple.style.color ="#42B983";
exmple.style.opacity =".4";
}, false)
- removeEventListener(与传入的时参数相同,因为匿名函数无法删除,所以函数必须不是匿名函数,必须向以下这样函数要有个名字。)
const hadel = function(){
exmple.style.color ="red";
exmple.style.opacity ="1";
}
btn.addEventListener("click", hadel, false)
btn.removeEventListener("click", hadel, false)
跨浏览器事件处理程序
- EventUtil.addHandler接收三个参数(“要操作的元素”, “事件名称”, ‘事件处理程序函数)
const EventUtil = {
addHandler: function(element, type, handler){
if(element.addEventListener){
element.addEventListener(type, handler, false);
}else if(element.attachEvent){
element.attachEvent("on" + type, handler);
}else {
element["on" + type] = handler;
}
},
removeHandler: function(element, type, handler){
if(element.removeEventListener){
element.removeEventListener(type, handler, false);
}else if(element.detachEvent){
element.detachEvent("on" + type, handler);
}else {
element["on" + type] = null;
}
}
}
const exmple = document.getElementById("exmple");
const btn = document.getElementById("btn");
const hadel = function(){
alert("hello")
}
EventUtil.addHandler(btn, "click", hadel)