This article mainly introduces how to implement javascript to block right-click events on an element and provides examples, you can refer to a friend who needs to trigger a custom menu by right-clicking on an element when making a small item recently, you can use a custom menu to edit the right-click entry. This requires that the default right-click menu be blocked.
The elements in IE and FF both have the oncontextmenu method. In FF, you only need to use the event. preventDefault () method to easily achieve this effect. IE does not support this method. In IE, the default event is blocked by returning false after the method is triggered.
In general, the blocking right-click event is globally blocked, that is, the right-click event is blocked at the document level. Now I want to implement the effect of blocking the default right-click event only in a specific area, other regions do not.
Through the experiment, I found that if the method bound under IE is "return false", the default action of right-clicking can be blocked at the document level. However, an element such as p is invalid.
Finally, we found that the event object in IE has a returnValue attribute. setting this attribute to false does not trigger the default right-click event. For example:
The Code is as follows:
Event. returnValue = false;
Just add this sentence to achieve the desired effect. Complete Demo code:
Block right-click on an element, default event DEMOScript 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
- View
- Sort
- Refresh
- Paste
- Paste Shortcut
- Property
Custom Context Menu Area
This effect is compatible with IE6 + and FF, but opera does not have the oncontextmenu method at all, so it cannot be implemented simply by this method. To implement this method, other means are required.