最近在做一個小東西的時候需要在某一個元素上“右擊”觸發一個自定義菜單,通過自定義的菜單對右擊的條目進行編輯。這就要求屏蔽默認的右鍵菜單
IE和FF下面的元素都有oncontextmenu這個方法,在FF下面只要通過event.preventDefault()方法就可以輕松實現這個效果。IE并不支持這個方法,在IE下面一般是通過觸發方法后return false來實現阻止默認事件的。
通常我們使用阻止右鍵事件是在全局阻止,即在document層面就將右鍵攔截,現在我想要實現的效果是只在特定的區域阻止默認的右鍵事件,而其他區域并不影響。
通過實驗我發現要是在IE下綁定的方法中return false后在document層面上可以實現阻止右鍵的默認行為。但是具體到某一個元素比如div,則失效。
最后通過查找手冊發現,IE下的event對象有一個returnValue屬性,如果將這個屬性設置為false則不會觸發默認的右鍵事件。類似如下:
只要加入這句就實現了我想要的效果。完整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>在某個元素上阻止鼠標右鍵默認事件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+,FF,但是opera壓根就沒有oncontextmenu這個方法所以也就不能簡單的通過這個方法實現,要想實現還需要通過其他的手段。
新聞熱點
疑難解答