Home >Web Front-end >JS Tutorial >Example of calling up context menu with js_javascript skills

Example of calling up context menu with js_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:25:111166browse

The example in this article describes the example code of calling up the context menu through js, and shares it with you for your reference. The details are as follows:

Principle
When the user right-clicks, a contextmenu event will be triggered. By default, the browser's default context menu will be triggered. By manually blocking this default behavior, the custom context menu will then be displayed. This menu can be hidden when the user clicks.
Code
1.html

<div id="box" style="color:red;width: 100%;height:1000px;" >
 <div id="left" style="float:left;width:500px;margin-left: 50px;height:500px;background: #cdeddf;">
  
 </div> 
 <div id="right" style="float:right;width:600px;margin-right: 50px;height:500px;background: #cdeaae;">
 </div>
 <ul id="menu" style="position: absolute;visibility: hidden;list-style: none;">
  <li>按钮1</li>
  <li>按钮2</li>
  <li>按钮3</li>
 </ul>
</div>

2.js

// 添加contextmenu事件
 var right = document.getElementById("right");
 EventUtil.addEventListener(right, "contextmenu", function(event) {
 event = EventUtil.getEvent(event);
 EventUtil.preventDefault(event);
 var menu = document.getElementById("menu");
 
 // 获取鼠标右击时的坐标,并设置上下文菜单出现位置
 page = EventUtil.getPagePosition(event); 
 menu.style.left = page.pageX + "px";
 menu.style.top = page.pageY + "px";
 menu.style.visibility = "visible";
 });
 
 // 添加隐藏上下文菜单事件
 EventUtil.addEventListener(document, "click", function(event) {
 var menu = document.getElementById("menu");
 menu.style.visibility = "hidden";
 });

The EventUtil that appears in the code is introduced in this article: "How to use js cross-browser event listeners and event objects"

The above is the entire content of this article. I will teach you how to bring up the context menu in js. I hope it will be helpful to your learning.

Statement:
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