什么是上下文菜单呢?
也就是说菜单和页面的某些区域有关,比如右键点击某块区域出现菜单,这个就叫上下文菜单。
下面我们给id="area"的div设置右键菜单
例子如下:
html页面代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hello world</title>
<script src="./event.js"></script>
</head>
<body onload="onLoad()">
<div id="area" style="background-color: red;width: 300px;height: 300px;">
</div>
</body>
</html>
<html>
<head>
<meta charset="UTF-8">
<title>hello world</title>
<script src="./event.js"></script>
</head>
<body onload="onLoad()">
<div id="area" style="background-color: red;width: 300px;height: 300px;">
</div>
</body>
</html>
event.js代码:
const electron = require('electron');
const remote = electron.remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
function onLoad(){
const menu = new Menu();
const win = remote.getCurrentWindow();
var menuChildItem1 = new MenuItem({label:'打开',click:()=>{}});//创建一个子菜单项
var menuChildItem2 = new MenuItem({label:'保存',click:()=>{}});//创建一个子菜单项
var menuItem1 = new MenuItem({label:'文件',submenu:[menuChildItem1,menuChildItem2]});//创建一个顶级菜单项,将子菜单项添加到submenu中
var menuChildItem3 = new MenuItem({label:'复制',click:()=>{}});//创建一个子菜单项
var menuChildItem4 = new MenuItem({label:'粘贴',click:()=>{}});//创建一个子菜单项
var menuItem2 = new MenuItem({label:'编辑',submenu:[menuChildItem3,menuChildItem4]});
menu.append(menuItem1);//将菜单项添加到menu中
menu.append(menuItem2);//将菜单项添加到menu中
//给id=area的div区域添加右键菜单
area.addEventListener('contextmenu',function(e){
e.preventDefault();//阻止默认行为
x = e.x;//鼠标右键点击的横坐标
y = e.y;//鼠标右键点击的纵坐标
menu.popup({x:x,y:y});
return false;
});
}
const remote = electron.remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
function onLoad(){
const menu = new Menu();
const win = remote.getCurrentWindow();
var menuChildItem1 = new MenuItem({label:'打开',click:()=>{}});//创建一个子菜单项
var menuChildItem2 = new MenuItem({label:'保存',click:()=>{}});//创建一个子菜单项
var menuItem1 = new MenuItem({label:'文件',submenu:[menuChildItem1,menuChildItem2]});//创建一个顶级菜单项,将子菜单项添加到submenu中
var menuChildItem3 = new MenuItem({label:'复制',click:()=>{}});//创建一个子菜单项
var menuChildItem4 = new MenuItem({label:'粘贴',click:()=>{}});//创建一个子菜单项
var menuItem2 = new MenuItem({label:'编辑',submenu:[menuChildItem3,menuChildItem4]});
menu.append(menuItem1);//将菜单项添加到menu中
menu.append(menuItem2);//将菜单项添加到menu中
//给id=area的div区域添加右键菜单
area.addEventListener('contextmenu',function(e){
e.preventDefault();//阻止默认行为
x = e.x;//鼠标右键点击的横坐标
y = e.y;//鼠标右键点击的纵坐标
menu.popup({x:x,y:y});
return false;
});
}