javascript實現(xiàn)在某個元素上阻止鼠標(biāo)右鍵事件的方法和實例

字號:


    最近在做一個小東西的時候需要在某一個元素上“右擊”觸發(fā)一個自定義菜單,通過自定義的菜單對右擊的條目進行編輯。這就要求屏蔽默認(rèn)的右鍵菜單
    IE和FF下面的元素都有oncontextmenu這個方法,在FF下面只要通過event.preventDefault()方法就可以輕松實現(xiàn)這個效果。IE并不支持這個方法,在IE下面一般是通過觸發(fā)方法后return false來實現(xiàn)阻止默認(rèn)事件的。
    通常我們使用阻止右鍵事件是在全局阻止,即在document層面就將右鍵攔截,現(xiàn)在我想要實現(xiàn)的效果是只在特定的區(qū)域阻止默認(rèn)的右鍵事件,而其他區(qū)域并不影響。
    通過實驗我發(fā)現(xiàn)要是在IE下綁定的方法中return false后在document層面上可以實現(xiàn)阻止右鍵的默認(rèn)行為。但是具體到某一個元素比如div,則失效。
    最后通過查找手冊發(fā)現(xiàn),IE下的event對象有一個returnValue屬性,如果將這個屬性設(shè)置為false則不會觸發(fā)默認(rèn)的右鍵事件。類似如下:
    代碼如下:
    event.returnValue = false;
    只要加入這句就實現(xiàn)了我想要的效果。完整Demo代碼:
    03 <head>
    04 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    05 <title>在某個元素上阻止鼠標(biāo)右鍵默認(rèn)事件DEMO</title>
    06 <style>
    07 body{font-size:12px; line-height:24px; font-family:Arial, Helvetica, sans-serif;}
    08 #activeArea{width:300px;height:200px; background:#06C; color:#fff;}
    09 #cstCM{ width:120px; background:#eee; border:1px solid #ccc; position:absolute; }
    10 #cstCM ul{margin:0; padding:0;}
    11 #cstCM ul li{ list-style:none;padding:0 10px; cursor:default;}
    12 #cstCM ul li:hover{ background:#009; color:#fff;}
    13 .splitTop{ border-bottom:1px solid #ccc;}
    14 .splitBottom{border-top:1px solid #fff;}
    15 </style>
    16 <script>
    17 function customContextMenu(event){
    18 event.preventDefault ? event.preventDefault():(event.returnValue = false);
    19 var cstCM = document.getElementById('cstCM');
    20 cstCM.style.left = event.clientX + 'px';
    21 cstCM.style.top = event.clientY + 'px';
    22 cstCM.style.display = 'block';
    23 document.onmousedown = clearCustomCM;
    24 }
    25 function clearCustomCM(){
    26 document.getElementById('cstCM').style.display = 'none';
    27 document.onmousedown = null;
    28 }
    29 </script>
    30 </head>
    31
    32 <body>
    33 <div id="cstCM">
    34 <ul>
    35 <li>View</li>
    36 <li>Sort By</li>
    37 <li>Refresh</li>
    38 <li>Paste</li>
    39 <li>Paste Shortcut</li>
    40 <li>Property</li>
    41 </ul>
    42 </div>
    43 <div id="activeArea" oncontextmenu = "customContextMenu(event)">
    44 Custom Context Menu Area
    45 </div>
    46 </body>
    47 </html>
    這個效果兼容IE6+,F(xiàn)F,但是opera壓根就沒有oncontextmenu這個方法所以也就不能簡單的通過這個方法實現(xiàn),要想實現(xiàn)還需要通過其他的手段。