本节主要介绍Native UI API 中菜单栏的使用,菜单栏分为两类:一类是普通菜单栏,另一类是上下文菜单栏(右键弹出)。
(一)例子
<span style="font-size:14px;"><!DOCTYPE html>
<html>
<head>
<title>menuDemo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>menu api 测试</h1>
<script>
// Load native UI library
var gui = require('nw.gui');
var win = gui.Window.get();
//创建window menu
var windowMenu = new gui.Menu({
type: 'menubar'
});
var windowSubmenu = new gui.Menu();
var subMenuItem = new gui.MenuItem({
label: '子菜单项'
});
windowSubmenu.append(subMenuItem);
windowMenu.append(
new gui.MenuItem({
label: '子菜单',
submenu: windowSubmenu
})
);
win.menu = windowMenu;
// Create an empty menu
var menu = new gui.Menu();
// Add some items
menu.append(new gui.MenuItem({
label: 'Item A'
}));
menu.append(new gui.MenuItem({
label: 'Item B'
}));
menu.append(new gui.MenuItem({
type: 'separator'
}));
menu.append(new gui.MenuItem({
label: 'Item C'
}));
document.body.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
menu.popup(10, 10);
return false;
});
</script>
</body>
</html></span>
(二)函数参考
new Menu([option])new Menu({
<span style="white-space:pre"> </span>type: 'menubar'
});
Menu.items
for (var i = 0; i < menu.items.length; ++i) {
var element = document.createElement('div');
element.appendChild(document.createTextNode(menu.items[i].label));
document.body.appendChild(element);
}
document.body.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
menu.popup(ev.x, ev.y);
return false;
});
MenuItem.click
menu.append(menuitem);
menuitem.click = function() {
console.log('clicked');
};
console.log(menu.items[0].click);
(三)创建上下文菜单
创建上下文菜单,需要在页面监听contextmenu 事件,然后控制弹出菜单。document.body.addEventListener('contextmenu', function (ev) {
ev.preventDefault();
menu.popup(10, 10);
return false;
});