场景
用HTML和CSS和JS构建跨平台桌面应用程序的开源库Electron的介绍以及搭建HelloWorld:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106413828
Electron怎样进行渲染进程调试和使用浏览器和VSCode进行调试:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106414541
在上面搭建好项目以及知道怎样进行调试后,那么Electron怎样实现菜单项。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
首先在renderer.js中引入Menu和MenuItem
const {remote} = require('electron'); const {Menu, MenuItem} = remote;
然后为了触发按钮弹出的操作,在index.html中添加一个按钮,并设置id
<button id="menuItem">弹出菜单</button>
然后在renderer.js中获取这个按钮并设置其点击事件,在点击事件中添加菜单项
var btnMenuItem=document.getElementById('menuItem'); btnMenuItem.onclick = PopMenu; function PopMenu() { const template = [ { label: "公众号:" }, { label: "霸道的程序猿" , click: () => { console.log("点击事件OK"); }}, { role: "undo"}, { role: "redo"}, { label: "旅游", type: "checkbox", checked: true}, { label: "吃", type: "checkbox", checked: true}, { label: "逛街", type: "checkbox", checked: false}, new MenuItem({label: "这是menuItem生成的菜单", click: ()=> { console.log("您点击了menuItem的菜单"); }}), { label: "子菜单测试", submenu: [ {label: "子菜单-1"}, {label: "子菜单-2"}, {label: "子菜单-3"} ] } ]; const menu = Menu.buildFromTemplate(template); menu.popup(); }
效果
上面的undo就是执行撤销的操作,redo就是重新执行撤销的操作,类似的操作还有
const template = [ { label: 'Edit', submenu: [ {role: 'undo'}, {role: 'redo'}, {type: 'separator'}, {role: 'cut'}, {role: 'copy'}, {role: 'paste'}, {role: 'pasteandmatchstyle'}, {role: 'delete'}, {role: 'selectall'} ] }, { label: 'View', submenu: [ {role: 'reload'}, {role: 'forcereload'}, {role: 'toggledevtools'}, {type: 'separator'}, {role: 'resetzoom'}, {role: 'zoomin'}, {role: 'zoomout'}, {type: 'separator'}, {role: 'togglefullscreen'} ] }, { role: 'window', submenu: [ {role: 'minimize'}, {role: 'close'} ] }, { role: 'help', submenu: [ { label: 'Learn More', click () { require('electron').shell.openExternal('https://electron.atom.io') } } ] } ] if (process.platform === 'darwin') { template.unshift({ label: app.getName(), submenu: [ {role: 'about'}, {type: 'separator'}, {role: 'services', submenu: []}, {type: 'separator'}, {role: 'hide'}, {role: 'hideothers'}, {role: 'unhide'}, {type: 'separator'}, {role: 'quit'} ] }) // Edit menu template[1].submenu.push( {type: 'separator'}, { label: 'Speech', submenu: [ {role: 'startspeaking'}, {role: 'stopspeaking'} ] } ) // Window menu template[3].submenu = [ {role: 'close'}, {role: 'minimize'}, {role: 'zoom'}, {type: 'separator'}, {role: 'front'} ] } const menu = Menu.buildFromTemplate(template) menu.popup();
效果