如何在 JavaScript 中捕获右键单击事件? [英] How can I capture the right-click event in JavaScript?

查看:29
本文介绍了如何在 JavaScript 中捕获右键单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止标准上下文菜单,并手动处理右键单击事件.

这是怎么做到的?

解决方案

使用 oncontextmenu 事件.

这是一个例子:

逻辑推理

并使用事件侦听器(归功于 rampion/4235426/how-can-i-capture-the-right-click-event-in-javascript/4236294#comment6115096_4236294" title="CC BY-SA 2.5">2011 年的评论):

el.addEventListener('contextmenu', function(ev) {ev.preventDefault();alert('成功!');返回假;}, 错误的);

不要忘记返回false,否则仍然会弹出标准上下文菜单.

如果您要使用自己编写的函数而不是 javascript:alert("Success!"),请记住在函数和 oncontextmenu 中都返回 false 属性.

I want to block the standard context menus, and handle the right-click event manually.

How is this done?

解决方案

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

这篇关于如何在 JavaScript 中捕获右键单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆