javascript 如何在javascript中模拟右键单击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17092328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to simulate right click in javascript
提问by mcgrailm
Ok, so i know i can simulate a click by running this code
好的,所以我知道我可以通过运行此代码来模拟点击
document.getElementById('recover').click();
the closest this i could find was cntextmenu so i tried
我能找到的最接近的是 cntextmenu 所以我试过了
document.getElementById('recover').contextmenu();
however this does nothing
然而这没有任何作用
Is it possible to right click and element to bring up the contextual menu so i can click an item on that list ? and if so could someone point me in the correct direction to accomplish such a goal ?
是否可以通过右键单击和元素来调出上下文菜单,以便我可以单击该列表中的一个项目?如果是这样,有人可以指出我实现这样一个目标的正确方向吗?
I've done some searching but the only thing i have found is jquery javascript capturing of the event not actually triggering the event
我已经做了一些搜索,但我发现的唯一一件事是 jquery javascript 捕获的事件并没有真正触发事件
回答by Ben McCormick
with jQuery
使用 jQuery
$('#recover').trigger({
type: 'mousedown',
which: 3
});
otherwise
否则
var element = document.getElementById('recover');
var e = element.ownerDocument.createEvent('MouseEvents');
e.initMouseEvent('contextmenu', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false,2, null);
return !element.dispatchEvent(e);
回答by Jordan
Sure, you can use the jQuery trigger() functionality.
当然,您可以使用 jQuery trigger() 功能。
$('#recover').trigger({
type: 'mousedown',
which: 3
});
Depending on what you're doing, you may wish to trigger a mouse down and then a mouse up, which could go like this:
根据您正在执行的操作,您可能希望先按下鼠标,然后再按下鼠标,这可能是这样的:
$('#recover').trigger({
type: 'mousedown',
which: 3
}).trigger({
type: 'mouseup',
which: 3
});
I'm not a big fan of chaining long commands like that, but whatever is most readable for your app is fine.
我不太喜欢链接这样的长命令,但是对于您的应用程序来说,最易读的任何东西都很好。