右击是Javascript事件吗?如果是,我该如何使用它?


当前回答

没有,但是你可以检测到在"onmousedown"事件中使用了什么鼠标按钮…然后从那里判断它是否是一个“右键”。

其他回答

使用jQuery库处理事件

$(window).on("contextmenu", function(e)
{
   alert("Right click");
})

正如其他人所提到的,可以通过通常的鼠标事件(鼠标下拉、鼠标上拉、单击)来检测鼠标右键。但是,如果您在弹出右键菜单时寻找触发事件,那么就找错地方了。右键单击/上下文菜单也可以通过键盘(shift+F10或上下文菜单键在Windows和一些Linux)访问。在这种情况下,你正在寻找的事件是oncontextmenu:

window.oncontextmenu = function ()
{
    showCustomMenu();
    return false;     // cancel default menu
}

至于鼠标事件本身,浏览器为事件对象设置了一个属性,可以从事件处理函数中访问:

document.body.onclick = function (e) {
    var isRightMB;
    e = e || window.event;

    if ("which" in e)  // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
        isRightMB = e.which == 3; 
    else if ("button" in e)  // IE, Opera 
        isRightMB = e.button == 2; 

    alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!");
} 

窗口。oncontextmenu - MDC

如果你想调用函数,而右击事件意味着我们可以使用以下

 <html lang="en" oncontextmenu="func(); return false;">
 </html>

<script>
function func(){
alert("Yes");
}
</script>

这是最简单的方法,它可以在所有浏览器上运行,除了应用程序web视图,如(CefSharp铬等…). 我希望我的代码能帮助到你,祝你好运!

const contentToRightClick=document.querySelector("div#contentToRightClick"); //const contentToRightClick=window; //If you want to add it into the whole document contentToRightClick.oncontextmenu=function(e){ e=(e||window.event); e.preventDefault(); console.log(e); return false; //Remove it if you want to keep the default contextmenu } div#contentToRightClick{ background-color: #eee; border: 1px solid rgba(0,0,0,.2); overflow: hidden; padding: 20px; height: 150px; } <div id="contentToRightClick">Right click on the box !</div>

下面的代码使用jQuery生成一个基于默认鼠标下拉和鼠标上拉事件的自定义右键单击事件。 它考虑到以下几点:

鼠标悬停时触发 仅当鼠标按下之前的同一元素时触发 这段代码特别适用于JFX Webview(因为上下文菜单事件不会在那里触发) 当键盘上的上下文菜单键被按下时,它不会触发(就像on('contextmenu',…)的解决方案一样)

$(function () { // global rightclick handler - trigger custom event "rightclick" var mouseDownElements = []; $(document).on('mousedown', '*', function(event) { if (event.which == 3) { mouseDownElements.push(this); } }); $(document).on('mouseup', '*', function(event) { if (event.which == 3 && mouseDownElements.indexOf(this) >= 0) { $(this).trigger('rightclick'); } }); $(document).on('mouseup', function() { mouseDownElements.length = 0; }); // disable contextmenu $(document).on('contextmenu', function(event) { event.preventDefault(); }); }); // Usage: $('#testButton').on('rightclick', function(event) { alert('this was a rightclick'); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="testButton">Rightclick me</button>