Class: MenuItem
Class: MenuItem
Добавляет элементы в основное меню и контекстное меню приложения.
Process: Main
See Menu
for examples.
new MenuItem(options)
acceleratorWorksWhenHidden
is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. Эта опция доступна пользователям для того, чтобы дать им возможность отключить ее, так как это возможно в родной macOS разработке.
Роли
Роли позволяют элементам класса menu иметь заранее определенные поведения.
Лучше всего указать role
для любого элемента меню, который соответствует стандартной роли, а не пытаться вручную реализовать поведение в функции click
. Встроенное поведение role
даст наилучшую нативную возможность использования.
Значения label
и accelerator
необязательны при использовании role
и по умолчанию будут присваиваться для каждой для каждой платформы.
Каждый элемент меню должен иметь role
или label
, или в случае разделителя type
.
Свойство role
может иметь следующие значения:
undo - Отменить
about
- Trigger a native about panel (custom message box on Window, which does not provide its own).redo - Восстановить
cut - Вырезать
copy - Копировать
paste - Вставить
pasteAndMatchStyle - Вставить и применить стиль
selectAll - Выделить все
delete - Удалить
minimize
- Свернуть текущее окно.close
- Закрыть текущее окно.quit
- Выйти из приложения.reload
- Перезагрузить текущее окно.forceReload
- Перезагрузить текущее окно, игнорировать кэш.toggleDevTools
- Включить инструмент разработчика для текущего окна.togglefullscreen
-Включить полноэкранный режим для текущего окна.resetZoom
- Сброс измененного масштаба страницы до исходного размера.zoomIn
- Увеличение масштаба страницы на 10%.zoomOut
- Уменьшение масштаба страницы на 10%.toggleSpellChecker
- Enable/disable builtin spell checker.fileMenu
- Полное меню "Файл" по умолчанию (Закрыть/Выйти)editMenu
- Whole default "Edit" menu (Undo, Copy, etc.).viewMenu
- Полное меню "Вид" по умолчанию (перезагрузка, переключение инструментов разработчика и т. д.)windowMenu
- Полное меню "Окно" по умолчанию (Свернуть, масштаб и т. д.).
На macOS доступны следующие дополнительные роли:
appMenu
- Полное меню "App" по умолчанию (О программе, службах и т. д.)hide
- Map to thehide
action.hideOthers
- Map to thehideOtherApplications
action.unhide
- Map to theunhideAllApplications
action.showSubstitutions
- Сопоставляется сorderFrontSubstitutionsPanel
.toggleSmartQuotes
- Сопоставляется сtoggleAutomaticQuoteSubstitution
.toggleSmartDashes
- Сопоставляется сtoggleAutomaticDashSubstitution
.toggleTextReplacement
- Сопоставляется сtoggleAutomaticTextReplacement
.startSpeaking
- Map to thestartSpeaking
action.stopSpeaking
- Map to thestopSpeaking
action.front
- Map to thearrangeInFront
action.zoom
- Map to theperformZoom
action.toggleTabBar
- Map to thetoggleTabBar
action.selectNextTab
- Map to theselectNextTab
action.selectPreviousTab
- Map to theselectPreviousTab
action.showAllTabs
- Map to theshowAllTabs
action.mergeAllWindows
- Сопоставляется сmergeAllWindows
.moveTabToNewWindow
- Сопоставляется сmoveTabToNewWindow
.window
- Подменю в меню "Окно".help
- Подменю в меню "Help".services
- Подменю меню "Сервисы". This is only intended for use in the Application Menu and is not the same as the "Services" submenu used in context menus in macOS apps, which is not implemented in Electron.RecentDocuments
- Подменю представляет собой меню "Открыть недавние".clearRecentDocuments
- Сопоставляется сclearRecentDocuments
.shareMenu
- The submenu is share menu. ThesharingItem
property must also be set to indicate the item to share.
When specifying a role
on macOS, label
and accelerator
are the only options that will affect the menu item. All other options will be ignored. Lowercase role
, e.g. toggledevtools
, is still supported.
[!NOTE] The
enabled
andvisibility
properties are not available for top-level menu items in the tray on macOS.
Свойства экземпляра
Для экземпляров MenuItem
доступны следующие свойства:
menuItem.id
A string
indicating the item's unique id, this property can be dynamically changed.
menuItem.label
A string
indicating the item's visible label.
menuItem.click
A Function
that is fired when the MenuItem receives a click event. It can be called with menuItem.click(event, focusedWindow, focusedWebContents)
.
event
KeyboardEventfocusedWindow
BaseWindowfocusedWebContents
WebContents
menuItem.submenu
Menu
(опционально), содержащие подменю пункты, если таковые имеются.
menuItem.type
A string
indicating the type of the item. Can be normal
, separator
, submenu
, checkbox
or radio
.
menuItem.role
string
(опционально) с указанием роли элемента, если установлено. Can be undo
, redo
, cut
, copy
, paste
, pasteAndMatchStyle
, delete
, selectAll
, reload
, forceReload
, toggleDevTools
, resetZoom
, zoomIn
, zoomOut
, toggleSpellChecker
, togglefullscreen
, window
, minimize
, close
, help
, about
, services
, hide
, hideOthers
, unhide
, quit
, startSpeaking
, stopSpeaking
, zoom
, front
, appMenu
, fileMenu
, editMenu
, viewMenu
, shareMenu
, recentDocuments
, toggleTabBar
, selectNextTab
, selectPreviousTab
, showAllTabs
, mergeAllWindows
, clearRecentDocuments
, moveTabToNewWindow
or windowMenu
menuItem.accelerator
An Accelerator
(optional) indicating the item's accelerator, if set.
menuItem.userAccelerator
Readonly macOS
An Accelerator | null
indicating the item's user-assigned accelerator for the menu item.
[!NOTE] This property is only initialized after the
MenuItem
has been added to aMenu
. Either viaMenu.buildFromTemplate
or viaMenu.append()/insert()
. Accessing before initialization will just returnnull
.
menuItem.icon
A NativeImage | string
(optional) indicating the item's icon, if set.
menuItem.sublabel
A string
indicating the item's sublabel.
menuItem.toolTip
macOS
A string
indicating the item's hover text.
menuItem.enabled
A boolean
indicating whether the item is enabled, this property can be dynamically changed.
menuItem.visible
A boolean
indicating whether the item is visible, this property can be dynamically changed.
menuItem.checked
A boolean
indicating whether the item is checked, this property can be dynamically changed.
Элемент меню checkbox
будет включать и выключать свойство checked
при его выборе.
Radio
пункт меню включит его свойство checked
при нажатии, и отключит это свойство для всех смежных пунктов в том же меню.
Вы можете добавить функцию click
для дополнительного поведения.
menuItem.registerAccelerator
A boolean
indicating if the accelerator should be registered with the system or just displayed.
This property can be dynamically changed.
menuItem.sharingItem
macOS
A SharingItem
indicating the item to share when the role
is shareMenu
.
This property can be dynamically changed.
menuItem.commandId
A number
indicating an item's sequential unique id.
menuItem.menu
Меню
, частью которого является элемент.