Recently, when I was making a small thing, I needed to "right-click" on an element to trigger a custom menu, and edit the right-clicked entry through a custom menu. This requires blocking the default right-click menu
The elements below IE and FF have the oncontextmenu method. Under FF, you can easily achieve this effect by using the event.preventDefault() method. IE does not support this method. Under IE, the default event is generally blocked by triggering the method and returning false.
Usually, we use the right-click event to block the global block, that is, the right-click is blocked at the document level. Now the effect I want to achieve is to only block the default right-click event in a specific area, while other areas do not affect it.
Through experiments, I found that if the return false in the bound method under IE can achieve the default behavior of blocking right-clicks at the document level. However, if a specific element such as a div is invalid.
Finally, through the search manual, I found that the event object under IE has a returnValue property. If this property is set to false, the default right-click event will not be triggered. Similar to the following:
The code copy is as follows:
event.returnValue = false;
Just add this sentence to achieve the effect I want. Complete Demo code:
<!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>Block the right mouse button default event on an element 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:#ffff;}.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>Refresh</li><li>Paste</li><li>Paste Shortcut</li><li>Property</li></ul></div><div id="activeArea" oncontextmenu = "customContextMenu(event)">Custom Context Menu Area</div></body></html>This effect is compatible with IE6+ and FF, but Opera does not have the oncontextmenu method at all, so it cannot be simply implemented through this method. To achieve it, other means are needed.