事件虽然右键单击(据我所知)触发 mousedown 事件,但在大多数情况下似乎忽略了 mousedown。我目前正在通过右键单击显示自定义上下文菜单,但我也希望能够在我右键单击时从列表中选择一个选项。截至目前,我认识到两个按钮的点击足以运行一些与 onmousedown 属性相关的javascript,但不足以选择当鼠标来自右键时鼠标悬停的选项。
有没有办法绕过浏览器的默认行为,即忽略右键单击的 mousedown 事件,或者让它认为 mousedown 是由左键生成的?
提前致谢。
事件虽然右键单击(据我所知)触发 mousedown 事件,但在大多数情况下似乎忽略了 mousedown。我目前正在通过右键单击显示自定义上下文菜单,但我也希望能够在我右键单击时从列表中选择一个选项。截至目前,我认识到两个按钮的点击足以运行一些与 onmousedown 属性相关的javascript,但不足以选择当鼠标来自右键时鼠标悬停的选项。
有没有办法绕过浏览器的默认行为,即忽略右键单击的 mousedown 事件,或者让它认为 mousedown 是由左键生成的?
提前致谢。
您可以使用该oncontextmenu
事件。
编辑:要模拟鼠标右键单击期间的默认单击行为,<option>
请在处理右键单击时将此代码放入事件处理程序中:
clickedOption.parentNode.selectedIndex = clickedOption.index;
如果你愿意使用jQuery,你可以简单地使用 mousedown:
$(document).bind('contextmenu', function(event)
{
// on right click
if (event.which == 3)
{
// prevent right click from being interpreted by the browser:
event.preventDefault();
$(document).mousedown(); // simulate left click
}
});
当然,您可以使用合适的选择器。这很棒,因为这样,右键单击仅用作对您网站的某些元素的左键单击。这样,大多数时候仍然可以按预期使用鼠标(取决于您的选择器)。
编辑:更好的例子
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#rightclick").bind('contextmenu', function(event) {
// on right click
if (event.which == 3)
{
// prevent right click from being interpreted by the browser:
event.preventDefault();
$(this).click(); // simulate left click
}
});
$('#rightclick').click(function() {
$(this).html("i have been clicked!");
});
});
</script>
</head>
<body>
<p>This is a web page.</p>
<div id="rightclick" style="width:200px; height:100px; background-color: orange">
Click me with the right or left mouse button. Both will work!
</div>
</body>
</html>