posted on 2013-12-28 15:19
疯狂 阅读(1662)
评论(0) 编辑 收藏
如果项目中没有使用诸如 jquery 之类的库,如何方便地为元素绑定事件,并兼容各种浏览器呢?下面这个简单的 utility 应该可以考虑。
var eventutility = {
addevent : function(el, type, fn) {
if(typeof addeventlistener !== "undefined") {
el.addeventlistener(type, fn, false);
} else if(typeof attachevent !== "undefined") {
el.attachevent("on" type, fn);
} else {
el["on" type] = fn;
}
},
removeevent : function(el, type, fn) {
if(typeof removeeventlistener !== "undefined") {
el.removeeventlistener(type, fn, false);
} else if(typeof detachevent !== "undefined") {
el.detachevent("on" type, fn);
} else {
el["on" type] = null;
}
},
gettarget : function(event) {
if(typeof event.target !== "undefined") {
return event.target;
} else {
return event.srcelement;
}
},
preventdefault : function(event) {
if(typeof event.preventdefault !== "undefined") {
event.preventdefault();
} else {
event.returnvalue = false;
}
}
};
使用方法示例:
var eventhandler = function(evt) {
var target = eventutility.gettarget(evt),
tagname = target.tagname;
if(evt.type === "click") {
if(tagname === "a" || tagname === "button") {
alert("you clicked on an a element, and the innerhtml is " target.innerhtml "!");
eventutility.preventdefault(evt);
}
} else if(evt.type === "mouseover" && tagname === "a") {
alert("mouseovered " target.innerhtml);
}
};
eventutility.addevent(document, "click", eventhandler);
eventutility.addevent(document, "mouseover", eventhandler);
eventutility.removeevent(document, "mouseover", eventhandler);