1. 程式人生 > >自定義菜單綁定

自定義菜單綁定

blog event 定位 logs pre color play cti 跨瀏覽器

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title></title>
 6 <style type="text/css">
 7     textarea{ width: 200px;height: 100px;}
 8     #menu{width: 50px;background: red; position: absolute; display: none;}
 9 </style>
10 </head>
11 <body> 12 <textarea id="text"></textarea> 13 <ul id="menu"> 14 <li>菜單1</li> 15 <li>菜單2</li> 16 <li>菜單3</li> 17 </ul> 18 </body> 19 </html>
<script>
 //跨瀏覽器添加事件
 function addEvent(obj,type,fn){
     
if (obj.addEventListener) { obj.addEventListener(type,fn,false); }else if (obj.attachEvent) { obj.attachEvent(‘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>

自定義菜單綁定