在Electron中,有没有一种方法可以根据用户右键单击的元素来启用/禁用上下文菜单中的特定MenuItem?我还需要有关单击了哪个确切元素的信息,并将该信息传递给上下文菜单功能。
例如,假设我的渲染器进程中包含以下html:
<p id="p1">First paragraph</p>
<p id="p2">Second paragraph</p>
<p id="p3">Third paragraph</p>
我在该窗口的上下文菜单如下所示:
var menu = new Menu();
menu.append(new MenuItem({label: "This menu item is always shown",}));
menu.append(new MenuItem({ // shown only when clicked on p1 or p3
label: "This menu is not always shown",
click: function(id){
// I want variable id to be an id of paragraph that I have clicked on
}
}));
因此,当我右键单击第一或第三段时,应该弹出一个包含2个项目的上下文菜单。但是,当我右键单击第二段时,应该弹出一个包含一项的上下文菜单。另外,我想将段落ID作为参数传递给上下文菜单函数,以便从那里知道我单击了哪个段落。
我会在contextmenu事件处理程序中动态(重新)创建上下文菜单:
在您的主要过程中:
如果加载远程内容,请不要打开nodeIntegration!
const { app, BrowserWindow } = require('electron');
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
在渲染器过程中:
请注意我如何“远程”加载Menu&MenuItem模块
<html>
<head>
<script>
const { remote } = require('electron');
const { Menu, MenuItem } = remote;
window.addEventListener('contextmenu', (e) => {
e.preventDefault();
const menu = new Menu();
menu.append(new MenuItem(new MenuItem({label: "This menu item is always shown"})));
if (e.target.id === "p1" || e.target.id === "p3") {
menu.append(new MenuItem({
label: "This menu is not always shown",
click: function(){
alert(`you clicked on ${e.target.id}`);
}
}));
}
menu.popup({ window: remote.getCurrentWindow() })
}, false)
</script>
</head>
<body>
<p id="p1">First paragraph</p>
<p id="p2">Second paragraph</p>
<p id="p3">Third paragraph</p>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句