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


当前回答

您可以使用事件窗口。Oncontextmenu,例如:

窗口。Oncontextmenu = function () { alert(右键) } <h1>请右键点击这里!< / h1 >

其他回答

在JQuery中,您可以使用以下代码检测它:

$('.target').on('contextmenu', function (evt) { evt.preventDefault(); }); $('.target').mouseup(function (evt) { if (evt.which === 3) { // right-click $(this).css("background-color","blue"); $(this).text("RIGHT"); } else if (evt.which === 1) { $(this).css("background-color","red"); $(this).text("LEFT"); } }); .target { display: inline-block; height: 100px; width: 100px; background: gray; text-align: center; color: white; font-size: 25px; vertical-align: middle; margin: 25px; } .container { width: 100%; height: 140px; background: #AAA; vertical-align: middle; text-align: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="target" id="target">Click</div> <div class="target" id="target">Right</div> <div class="target" id="target">Click me!</div> </div>

最简单的右击方式是使用

 $('classx').on('contextmenu', function (event) {

 });

然而,这不是跨浏览器的解决方案,浏览器的行为不同,特别是firefox和IE。我推荐下面的跨浏览器解决方案

$('classx').on('mousedown', function (event) {
    var keycode = ( event.keyCode ? event.keyCode : event.which );
    if (keycode === 3) {
       //your right click code goes here      
    }
});

窗口。Oncontextmenu =函数(e) { e.preventDefault () alert(右键) } <h1>请右键点击这里!< / h1 >

是的,它是一个javascript鼠标下拉事件。有一个jQuery插件也可以做到这一点

这是最简单的方法,它可以在所有浏览器上运行,除了应用程序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>