But sometimes we encounter such a problem. We want to prohibit visitors from using the right-click menu or block certain functions of the right-click menu. For example, in order to protect the content of the web page, we do not want visitors to view the source code of the web page through the right-click menu. We don’t want them to select, copy, etc. web content by right-clicking. When considering this problem, many web designers simply block the right-clicking. Instead of doing this, we might as well use scripts to implement a styled right-clicking menu and add it in Load our own content into this right-click menu. Let's try this idea out now.
The first thing we need to consider is to call a function through the right-click event of the mouse. This function is used to display the contents of the new right-click menu. We know that the right-click event of the mouse is called through document.oncontextmenu. If we define document.oncontextmenu = a certain function, we can call the new right-click menu. The key question is how to control the menu through this function. At the same time, the menu must be hidden through the form's click event document.body.onclick (generally refers to left-click). This process completes the pop-up and hiding of the right-click menu.
First, let’s take a look at this script code:
/*Initialization*/
<script language="JavaScript1.2">
/*If the current browser is Internet Explorer, document.all returns true*/
if (document.all && window.print) {
/*Select the display style of the menu box*/
ie5menu.className = menuskin;
/*The processing process of redirecting the right mouse button event is the custom program showmenuie5*/
document.oncontextmenu = showmenuie5;
/*The processing process of redirecting the left mouse button event is the custom program hidemenuie5*/
document.body.onclick = hidemenuie5;
}
</script>
Generally, the right mouse button event occurs after the page is loaded, so in order not to affect the loading speed of the page, we can put this code at the end of the page. This code is very simple. First check whether it is IE browser. If so, then the following definition should be valid. That is to say, when it is detected that the browser used by the client is IE, the function showmenuie5 is called when the user generates a right-click event, and the function hidemenuie5 is called when the user generates a left-click event.
Having solved the above problem, now we have to consider how to display and hide the menu through the function showmenuie5 and function hidemenuie5. Of course, the menu here is not a real right-click menu, but a div we made ourselves, and we put the things we want to put in this div. Call the function through mouse events to control its visibility, which achieves the same effect as using the right mouse button.