Home > Article > Web Front-end > Sharing a simple example of customizing the right-click menu using JS
This article mainly introducesJSAn example of simple implementation of custom right-click menu. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
RT, a simple example, just telling the principle
The code is as follows:
<p id="menu" style="width: 0;height: 0;background: cadetblue;position: absolute"></menu>
Suppose I want to make the p above Set it as a right-click menu and beautify it as you like.
The principle is to use contextmenuevent. When you right-click, this event will be triggered. The eventobject can get the distance clientX from the mouse to the upper left corner of the page. and clientY,
We can use these two attributes to control the horizontal and vertical offset of p, and return false to cancel the default behavior of the event, To simulate the browser's right-click menu.
document.oncontextmenu=function(e){ var x=e.clientX+'px'; var y=e.clientY+'px'; var node=document.querySelector('#menu'); node.style.left=x; node.style.top=y; node.style.width=100+'px'; node.style.height=100+'px'; return false; //很重要,不能让浏览器显示自己的右键菜单 }
Now is the closing part. The way to close the right-click menu is usually to left-click in the blank area.
document.onclick=function(e){ if(e.target.id!='menu') { var node=document.querySelector('#menu'); node.style.width=0; node.style.height=0; } }
This is just a basic idea, the core is the contextmenu event. On this basis, you can use CSS to beautify and upgrade at will, and add attributes such as transition to achieve the animation effect.
The above is the detailed content of Sharing a simple example of customizing the right-click menu using JS. For more information, please follow other related articles on the PHP Chinese website!