右击是Javascript事件吗?如果是,我该如何使用它?
当前回答
您可以使用事件窗口。Oncontextmenu,例如:
窗口。Oncontextmenu = function () { alert(右键) } <h1>请右键点击这里!< / h1 >
其他回答
是的,它是!
function doSomething(e) {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert('Rightclick: ' + rightclick); // true or false
}
您可能想尝试以下属性:
按钮- (caniuse); Which - (caniuse)(弃用)。
function onMouseDown(e)
{
if (e.which === 1 || e.button === 0)
{
console.log('Left mouse button at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 2 || e.button === 1)
{
console.log('Middle mouse button at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 3 || e.button === 2)
{
console.log('Right mouse button at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 4 || e.button === 3)
{
console.log('Backward mouse button at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 5 || e.button === 4)
{
console.log('Forward mouse button at ' + e.clientX + 'x' + e.clientY);
}
}
window.addEventListener("mousedown", onMouseDown);
document.addEventListener("contextmenu", function(e)
{
e.preventDefault();
});
相关:演示
操作系统
On Windows and Linux there are modifier keys Alt, Shift and Ctrl. On Mac there’s one more: Cmd, corresponding to the property metaKey... Even if we’d like to force Mac users to Ctrl+click – that’s kind of difficult. The problem is: a left-click with Ctrl is interpreted as a right-click on MacOS, and it generates the contextmenu event, not click like Windows/Linux. So if we want users of all operating systems to feel comfortable, then together with ctrlKey we should check metaKey. For JS-code it means that we should check if (event.ctrlKey || event.metaKey)...
在本章中,我们将详细介绍鼠标事件及其属性……
来源:https://amazon.com/dp/B07DZWLPG9
下面的代码使用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>
窗口。Oncontextmenu =函数(e) { e.preventDefault () alert(右键) } <h1>请右键点击这里!< / h1 >
添加一个e.preventDefault来阻止菜单出现(以防你不想要它) 窗口。Oncontextmenu =函数(e) { e.preventDefault (); 警报(“你点击”); } <标题>右键单击< / h1 >