Posted on 2013-12-28 15:19
疯狂 阅读(1713)
评论(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);