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代碼:
<!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=utf-8" /> <title>在某個元素上阻止鼠標(biāo)右鍵默認(rèn)事件DEMO</title> <style> body{font-size:12px; line-height:24px; font-family:Arial, Helvetica, sans-serif;} #activeArea{width:300px;height:200px; background:#06C; color:#fff;} #cstCM{ width:120px; background:#eee; border:1px solid #ccc; position:absolute; } #cstCM ul{margin:0; padding:0;} #cstCM ul li{ list-style:none;padding:0 10px; cursor:default;} #cstCM ul li:hover{ background:#009; color:#fff;} .splitTop{ border-bottom:1px solid #ccc;} .splitBottom{border-top:1px solid #fff;} </style> <script> function customContextMenu(event){ event.preventDefault ? event.preventDefault():(event.returnValue = false); var cstCM = document.getElementById('cstCM'); cstCM.style.left = event.clientX + 'px'; cstCM.style.top = event.clientY + 'px'; cstCM.style.display = 'block'; document.onmousedown = clearCustomCM; } function clearCustomCM(){ document.getElementById('cstCM').style.display = 'none'; document.onmousedown = null; } </script> </head> <body> <div id="cstCM" style="display:none;"> <ul> <li>View</li> <li>Sort By</li> <li class="splitTop">Refresh</li> <li class="splitBottom">Paste</li> <li class="splitTop">Paste Shortcut</li> <li class="splitBottom">Property</li> </ul> </div> <div id="activeArea" oncontextmenu = "customContextMenu(event)"> Custom Context Menu Area </div> </body> </html>
這個效果兼容IE6+,F(xiàn)F,但是opera壓根就沒有oncontextmenu這個方法所以也就不能簡單的通過這個方法實現(xiàn),要想實現(xiàn)還需要通過其他的手段。
相關(guān)文章
淺談js中Object.create()與new的具體實現(xiàn)與區(qū)別
本文主要介紹了js中Object.create()與new的具體實現(xiàn)與區(qū)別,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03web項目開發(fā)之JS函數(shù)防抖與節(jié)流示例代碼
這篇文章主要介紹了web項目開發(fā)之JS函數(shù)防抖與節(jié)流實現(xiàn)的示例代碼及原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09JavaScript 動態(tài)將數(shù)字金額轉(zhuǎn)化為中文大寫金額
JavaScript 將數(shù)字金額轉(zhuǎn)化為中文大寫金額的函數(shù)2009-05-05js利用與或運算符優(yōu)先級實現(xiàn)if else條件判斷表達(dá)式
利用與或運算符優(yōu)先級實現(xiàn)if else運算,讓你的代碼更精簡。2010-04-04