Home > Web Front-end > JS Tutorial > body text

JavaScript implementation method for customizing the right-click menu of any element_Basic knowledge

WBOY
Release: 2016-05-16 17:34:04
Original
1178 people have browsed it

1. Some concepts:

1. The mouse event has a bottom attribute: it returns an integer to indicate which mouse button was clicked.
BUG: Among the mouse events of IE and standard DOM, the only button attribute value with the same value is the "right-click" event, both of which return 2.

2. Event onmousedown: indicates the action of pressing the mouse button.
Event oncontextmenu: Another event triggered by clicking the mouse.

3. Method to interrupt the default event processing function: set returnValue=false in IE; call preventDefault() method in standard DOM.

4. Event object: ① In IE, the event object is an event attribute of the window object.

Disclaimer:

②In the standard DOM, the event object is the only parameter of the event processing function.

Disclaimer:

Solving compatibility:

2. Implementation:

< ;p id="p1">Uncle Cat is a fat white cat !

Cut
                                                                                                                 

window.onload=function(){
rightmenu('p1',' d1');
}
/****
* Encapsulate the right-click menu function:
* elementID The id of the element to customize the right-click menu
* menuID The id of the right-click menu DIv to be displayed
*/
function rightmenu(elementID,menuID){
 var menu=document.getElementById(menuID); //Get the menu object
var element=document.getElementById(elementID);//Get the clicked element with a custom right button
element.onmousedown=function(aevent){ //Set the processing function for pressing the right mouse button of the element
if(window.event)aevent=window.event; //Solve compatibilityif(aevent.button==2){ //When the value of the event attribute button is 2, the user pressed the right buttonDocument.oncontextmenu=function(aevent){ if(window.event){ aevent=window.event; aevent.returnValue=false; //Default right-click event handler for IE interruption top:' aevent.clientY 'px;' 'left:' aevent.clientX 'px;'
   //Position the menu relative to the mouse
  }
 }
 menu.onmouseout=function(){ //Set the menu to be hidden when the mouse moves out of the menu
 setTimeout(function(){menu.style.display="none";},400);
 }
}


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template