Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

javascript - 如何将自定义右键单击菜单添加到网页?(How to add a custom right-click menu to a webpage?)

I want to add a custom right-click menu to my web application.

(我想在我的Web应用程序中添加自定义右键单击菜单。)

Can this be done without using any pre-built libraries?

(这可以在不使用任何预先构建的库的情况下完成吗?)

If so, how to display a simple custom right-click menu which does not use a 3rd party JavaScript library?

(如果是这样,如何显示一个不使用第三方JavaScript库的简单自定义右键单击菜单?)

I'm aiming for something like what Google Docs does.

(我的目标是Google Docs的功能。)

It lets users right-click and show the users their own menu.

(它允许用户右键单击并向用户显示他们自己的菜单。)

NOTE: I want to learn how to make my own versus using something somebody made already since most of the time, those 3rd party libraries are bloated with features whereas I only want features that I need so I want it to be completely hand-made by me.

(注意:我想学习如何制作自己的东西而不是使用某些人已经制作的东西,因为大多数时候,那些第三方库充满了功能,而我只想要我需要的功能,所以我希望它完全由手工制作我。)

  ask by Registered User translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answering your question - use contextmenu event, like below:

(回答你的问题 - 使用contextmenu事件,如下所示:)

 if (document.addEventListener) { document.addEventListener('contextmenu', function(e) { alert("You've tried to open context menu"); //here you draw your own menu e.preventDefault(); }, false); } else { document.attachEvent('oncontextmenu', function() { alert("You've tried to open context menu"); window.event.returnValue = false; }); } 
 <body> Lorem ipsum... </body> 

But you should ask yourself, do you really want to overwrite default right-click behavior - it depends on application that you're developing.

(但是你应该问自己,你真的想要覆盖默认的右键单击行为 - 这取决于你正在开发的应用程序。)


JSFIDDLE

(的jsfiddle)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...