首页 > 代码库 > 跨浏览器的事件对象
跨浏览器的事件对象
一、跨浏览器的事件对象
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>
跨浏览器的事件对象
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。