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

黄舟
Release: 2017-05-31 10:09:33
Original
1529 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:

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 eventobjectcan get the distance clientX from the mouse to the upper left corner of the page. and clientY,

We can use these twoattributesto control the horizontal and vertical offset of p, and return false to cancel the defaultbehaviorof 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; //很重要,不能让浏览器显示自己的右键菜单 }
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!='menu')   {     var node=document.querySelector('#menu');     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 theanimationeffect.

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!