疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 480, comments - 486, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

JavaScript 跨浏览器事件处理(转)

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

只有注册用户登录后才能发表评论。


网站导航: