跨浏览器的事件对象

跨浏览器的事件对象

一、跨浏览器的事件对象

var 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;
}
},
//获取事件
getEvent: function (event) {
return event ? event : window.event;
},
//获取事件元素目标
getTarget: function (event) {
return event.target || event.srcElement;
},
//取消事件的默认行为
preventDefault: function (event) {
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
},
///移除事件
removeHandler: function (element, type, handler) {
if (element.removeEvenListener) {
element.removeEvenListener(type, handler, false);
} else if (element.detachEvent) {
element.detachEvent("on" + type, handler);
} else {
element["on" + type] = null;
}
},
stopPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
}
else {
event.cancelBubble = true;
}
}
};

二、右键菜单demo

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="myDiv">
点击右键
</div>
<ul id="myMenu" style="position: absolute; visibility: hidden; background-color: silver;">
<li><a href="http://baidu.com">baidu.com</a>
</li>
<li><a href="http://zhihu.com">zhihu.com</a>
</li>
</ul>
<script src="../Scripts/EventUtil.js"></script>
<script>
EventUtil.addHandler(window, "load", function (event) {
var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "contextmenu", function (event) {
event = EventUtil.getEvent(event);
EventUtil.preventDefault(event); var menu = document.getElementById("myMenu");
menu.style.left = event.clientX + "px";
menu.style.top = event.clientY + "px";
menu.style.visibility = "visible"; }); EventUtil.addHandler(document, "click", function (event) {
document.getElementById("myMenu").style.visibility = "hidden";
});
}) EventUtil.addHandler(window, "beforeunload", function (event) {
event = EventUtil.getEvent(event);
var message = "您确定要离开当前页";
event.returnValue = message;
return message;
});
</script>
</body>
</html>
05-11 09:21