Js custom right mouse button implementation principle and source code

  • 2020-03-30 03:27:27
  • OfStack

Today, I will record the right mouse button of js custom definition. Also, I will first decompose its implementation principle:

1. Screen the default right click event; (at one point I thought it was the default event)

2. Hiding a ul; (this I also pedantic think is worth this operation is div, sweat)

3. Response to the right mouse click to show the hidden ul;

4, the mouse re - click, ul is hidden again

In this way, we need to do a lot of things are not simple, first on the code:

HTML part


<ul id="testRight" style="width: 100px;background-color: yellow;position: absolute;z-index: 100;"> 
<li><a href="#"> start </a></li> 
<li><a href="#"> suspended </a></li> 
<li><a href="#"> Bye bye </a></li> 
</ul>

Javascript part:


window.onload=function(){ 
var forRight=document.getElementById("testRight");//Getting an object, now all too familiar
forRight.style.display="none"; 
var title=forRight.getElementsByTagName("li"); 

for(var i=0;i<title.length;i++){ 
title[i].onmouseover=function(){ 
this.classname="active";//We can call other events here
}; 
title[i].onmouseout=function(){//There are also two mouse events
this.classname=""; 
}; 
} 

document.oncontextmenu=function(event){//This is the key to implementation
var event=event||window.event;//That's not even a problem
forRight.style.display="block"; 
forRight.style.left=event.clientX+"px"; 
forRight.style.top=event.clientY+"px";//The coordinates of the mouse
return false;//False is returned here to mask the default event
}; 
document.onclick=function(){//Just to make it look better
forRight.style.display="none"; 
}; 
};


So let's take a look at the key point of today's recording: document.oncontextmenu this event returns false to mask the default event, and if we don't write anything else, we just write return in this event, which looks like this


document.oncontextmenu=function(){ 
return false; 
}

In this case, the right click will not appear any response. Then return to see the whole event application, it seems that in addition to this event, the other are relatively familiar with the event, but the integration of the event is always lacking, the key is the idea of creativity, but no matter where more, the whole first, but to read 3,000, not to write only to ask. Prick, prick, prick...


Related articles: