/* CSS for Christian's Sandbox */
#contextmenu {
display: none;
position: absolute;
left: 0px;
top: 0px;
border: 1px solid #aaa;
border-radius: 2px;
background-color: #ccc;
color: #000;
}
sandbox.js:
/* JavaScript for Christian's Sandbox */
document.onload = function() { // Make sure this all works
// Context menu script
var contextmenudiv = document.getElementById("contextmenu"),
contextmenu = {
hide: function(event) {
// Hide the context menu div
contextmenudiv.style.display = "none";
// Remove the event listener
document.removeEventListener("click", contextmenu.hide, true);
},
};
document.addEventListener("contextmenu", function(event) {
// Prevent the browser from opening the default context menu
event.preventDefault();
// Move the context menu to where the mouse is with respect to the page
contextmenudiv.style.left = (event.pageX + scrollX) + "px";
contextmenudiv.style.top = (event.pageY + scrollY) + "px";
// Display it
contextmenudiv.style.display = "block ";
// When you click somewhere else, hide it
document.addEventListener("click", contextmenu.hide, true);
}, true);
}
我把它修复了。 我做的是:我将
contextmenudiv = document.getElementById("contextmenu")
document.onload
.。
这里是我的新代码:/* JavaScript for Christian's Sandbox */
// Context menu script
var contextmenudiv,
contextmenu = {
hide: function(event) {
if (event.button == 0) {
event.preventDefault();
// Hide the context menu div
contextmenudiv.style.display = "none";
// Remove the event listener
document.removeEventListener("click", contextmenu.hide, true);
}
},
};
document.addEventListener("contextmenu", function(event) {
contextmenudiv = document.getElementById("contextmenu");
// Prevent the browser from opening the default context menu
event.preventDefault();
// Move the context menu to where the mouse is with respect to the page
contextmenudiv.style.left = (event.pageX + scrollX) + "px";
contextmenudiv.style.top = (event.pageY + scrollY) + "px";
// Display it
contextmenudiv.style.display = "block";
// When you click somewhere else, hide it
document.addEventListener("click", contextmenu.hide, true);
}, true);
我知道这是很多年后,但是如果现在有所帮助,我制作了一个自定义上下文菜单库,称为ContestmentMenu+,最终将在Universe-os.com.c.com.
中找到。
但是目前,我不妨告诉您如何使用它并提供源代码。 ContextMenu+是宇宙开发人员Squeakyllama1的图书馆。它使您可以轻松地将自定义上下文菜单添加到文档中的不同元素中,并禁用默认上下文菜单。目前众所周知,这可以在Chrome上完美工作。要启用元素的自定义上下文菜单,请添加属性
data-context-enabled
。带有一个选项“取消”(关闭菜单)的默认上下文菜单将填充右键单击操作。
要设置自定义内容,请添加属性data-custom-dct
。此属性应包括您的选项,以下是自定义内容的示例:
<button data-context-enabled data-custom-dct='[{"label":"Page Options","submenu":[{"label":"Force Reload Page","action":"forcereloadpage()"},{"label":"Close Page","action":"closepage()"} ]},{"label":"Reload Page","action":"reloadpage()"}, {"label":"Cancel"}]'>Example</button>