Javascript implements methods and instances that block right click events on an element

  • 2020-03-30 03:40:53
  • OfStack

Recently, I needed to "right click" on an element to trigger a custom menu to edit the right click entry. This requires that the default right-click menu be blocked

Usually, we use the right click event to block the right click globally, that is, to intercept the right click at the document level. Now, what I want to achieve is to block the default right click event only in a certain area, and not in other areas.

Through experiments, I found that if return false in the method bound under IE, the default behavior of preventing right-click can be implemented at the document level. But specific to a certain element, such as div, is invalid.

Finally, it is found by looking up the manual 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:


event.returnValue = false;

Just add this sentence and I get what 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> Prevents right-click default events 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:#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>

This effect is compatible with IE6+, FF, but opera doesn't have the oncontextmenu method at all, so it can't be easily implemented through this method, and other means are needed to achieve it.


Related articles: