我正在使用一个名为contextmenu的(非常老)的jQuery插件来替换某些元素上的右键单击上下文菜单。可以在here中找到此插件的源。
您将上下文菜单附加到元素,如下所示:
$(".class").contextMenu('menu_template', {
menuStyle: {
border: '0px',
},
itemStyle: {
},
itemHoverStyle: {
},
onShowMenu: function(e, menu) {
},
other stuff ....
})
另外,我想手动触发此菜单,并认为最简单的方法是模拟对该元素的右键单击。
我试过了:
$('.class').triggerHandler('contextmenu');
和
$('.class').trigger({
type:'mousedown',
button:2
}).trigger({
type:'mouseup',
button:2
});
和
$('.class').trigger({
type:'mousedown',
which:3
}).trigger({
type:'mouseup',
which:3
});
而只是
$('.class').trigger({
type:'mousedown',
which:3
})
这些都不起作用。
我确信这与该插件将自身自身附加到元素并覆盖上下文菜单有关,但是我不是JavaScript专家,所以不确定发生了什么。
如何手动触发此菜单出现?
最佳答案
你尝试过这样的事情吗?
$(document).mousedown(function(e) {
if (e.button == 2) {
$("span.demo1").trigger("contextmenu");
}
return true;
});
SNIPPET
$(document).ready(function() {
$(document).bind("contextmenu", function(e) {
e.preventDefault();
});
$('span.demo1').contextMenu('myMenu1', {
bindings: {
'open': function(t) {
alert('Trigger was ' + t.id + '\nAction was Open');
},
'email': function(t) {
alert('Trigger was ' + t.id + '\nAction was Email');
},
'save': function(t) {
alert('Trigger was ' + t.id + '\nAction was Save');
},
'delete': function(t) {
alert('Trigger was ' + t.id + '\nAction was Delete');
}
}
});
});
$(document).mousedown(function(e) {
if (e.button == 2) {
var element = document.getElementById("quickDemo"),
ev;
if (document.createEvent) {
ev = new MouseEvent("contextmenu", {
screenX: 0,
screenY: 0,
clientX: element.offsetLeft,
clientY: element.offsetTop + element.offsetHeight,
ctrlKey: false,
shiftKey: false,
altKey: false,
metaKey: false,
button: 2
});
element.dispatchEvent(ev);
} else {
ev = document.createEventObject();
element.fireEvent('contextmenu', ev);
}
}
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://www.trendskitchens.co.nz/jquery/contextmenu/jquery.contextmenu.r2.js"></script>
<div class="contextMenu" id="myMenu1" style="display: none;">
<ul>
<li id="open">
<img src="folder.png">Open</li>
<li id="email">
<img src="email.png">Email</li>
<li id="save">
<img src="disk.png">Save</li>
<li id="delete">
<img src="cross.png">Delete</li>
</ul>
</div>
<span class="demo1" id="quickDemo" style="float:right;border: 1px solid #888;">
<b>DEMO</b> right-click me!!
</span>