如何选择或聚焦对象时,如何将右键单击作为左键单击

时间:2011-08-08 20:57:24

标签: javascript right-click onmousedown selectonemenu mousedown

事件虽然右键单击(据我所知)触发了一个mousedown事件,但在大多数情况下,mousedown似乎被忽略了。我正在通过右键单击显示自定义上下文菜单,但我也希望能够在右键单击时从列表中选择一个选项。截至目前,我认识到来自两个按钮的点击足以运行与onmousedown属性相关联的一些javascript,但是当mousedown来自右键时,选择鼠标结束的选项还不够。

有没有办法绕过浏览器忽略右键单击的mousedown事件的默认行为,或者愚弄它认为是由左键生成了mousedown?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以使用oncontextmenu事件。

修改:要在鼠标右键单击期间模拟<option>上的默认点击行为,请在处理右键单击时将此代码放入事件处理程序中:

clickedOption.parentNode.selectedIndex = clickedOption.index;

答案 1 :(得分:-1)

如果您愿意使用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>
相关问题