问题描述
目前,我的代码(见下文)正在为操作系统提供右键单击菜单。我的目标是添加自定义样式,例如更改背景颜色或添加填充。我想知道我当前的代码是否可以这样做,或者我是否必须使用不同的包。
这是我的代码:
const remote = electron.remote
const Menu = remote.Menu
const MenuItem = remote.MenuItem
const sceneCardElements = document.querySelectorAll('.scene-card')
let rightClickPosition = null
const sceneCardMenu = new Menu()
const sceneCardMenuItem1 = new MenuItem({
label: 'Edit',click: () => {
remote.getCurrentwindow().loadFile('./scenesettings.html')
}
})
sceneCardMenu.append(sceneCardMenuItem1)
sceneCardElements.forEach((sceneCardElement) => {
if (sceneCardElement == null) return
sceneCardElement.addEventListener('contextmenu',(e) => {
e.preventDefault()
rightClickPosition = {x: e.x,y: e.y}
sceneCardMenu.popup(remote.getCurrentwindow())
},false)
})
这是它返回的屏幕截图:
谢谢!
解决方法
因此,我最终使用了一个名为 tippy.js 的库并使用了它们的右键菜单 template
这里是以后看这篇文章的人的最终代码:
// Get the Element you want to Right-Click
const element = document.querySelector('#rightClickable')
// Define the Tippy.js Rightclick Element
const instance = tippy(element,{
// Get the Template you made into JS
content: document.getElementById('rightClickMenuTemplate').innerHTML,placement: 'right-start',trigger: 'manual',interactive: true,arrow: false,offset: [0,0],allowHTML: true,});
// Add the Event Listener
element.addEventListener('contextmenu',(event) => {
event.preventDefault();
instance.setProps({
getReferenceClientRect: () => ({
width: 0,height: 0,top: event.clientY,bottom: event.clientY,left: event.clientX,right: event.clientX,}),});
instance.show();
});
<!-- Right Click the Text Below -->
<p id="rightClickable">Right Click Me!</p>
<!-- Right-Click Menu Template Used by Tippy.js -->
<div id="rightClickMenuTemplate" style="display: none; visibility: hidden;">
<strong>Hi from the Right-Click Menu</strong>
</div>
<!-- Import Tippy.js -->
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>