<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>匿名函数和闭包</title> <script> //跨浏览器添加事件 function addEvent(obj, type, fn) { if (obj.addEventListener) { obj.addEventListener(type, fn, false); } else if (obj.attachEvent) { obj.attachEvent('on' + type, fn); } } //跨浏览器移除事件 function removeEvent(obj, type, fn) { if (obj.removeEventListener) { obj.removeEventListener(type, fn, false); } else if (obj.detachEvent) { obj.detachEvent('on' + type, fn); } } function preDef(evt) { var e = evt || window.event; if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } addEvent(window, 'load', function () { var text = document.getElementById('text'); addEvent(text, 'contextmenu', function (evt) { preDef(evt); var menu = document.getElementById('menu'); var e = evt || window.event; menu.style.left = e.clientX + 'px'; menu.style.top = e.clientY + 'px'; menu.style.display = 'block'; addEvent(document, 'click', function () { menu.style.display = 'none'; }); }); }); </script> <style type="text/css"> #menu { width:50px; background:orange; position:absolute; display:none; } </style> </head> <body> <textarea id="text" style="width:200px;height:100px;"></textarea> <ul id="menu" > <li>菜单1</li> <li>菜单2</li> <li>菜单3</li> </ul> </body> </html>