Home > Web Front-end > JS Tutorial > Sharing a simple example of customizing the right-click menu using JS

Sharing a simple example of customizing the right-click menu using JS

黄舟
Release: 2017-05-31 10:09:33
Original
1659 people have browsed it

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>
Copy after login

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+&#39;px&#39;;

  var y=e.clientY+&#39;px&#39;;

  var node=document.querySelector(&#39;#menu&#39;);

  node.style.left=x;

  node.style.top=y;

  node.style.width=100+&#39;px&#39;;

  node.style.height=100+&#39;px&#39;;

  return false; //很重要,不能让浏览器显示自己的右键菜单

}
Copy after login

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!=&#39;menu&#39;)

  {

    var node=document.querySelector(&#39;#menu&#39;);

    node.style.width=0;

    node.style.height=0;

  }
}
Copy after login

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!

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