How can I make a right-click behave as a left-click for the purpose of selecting or focusing an object

不打扰是莪最后的温柔 提交于 2019-12-24 03:49:09

问题


Event though a right-click (as far as I know) fires a mousedown event, that mousedown seems to be ignored in most cases. I'm currently working on displaying a custom context menu via a right-click, but I'd also like to be able to select an option from a list while I'm right-clicking. As of right now my recognizes the click from both buttons enough to run some javascript tied to the onmousedown attribute but not enough to select the option the mouse is over when the mousedown comes from the right button.

Is there a way to bypass a browser's default behavior of ignoring the mousedown event of a right-click or fool it into thinking the mousedown was generated by the left button instead?

Thanks in advance.


回答1:


You can use the oncontextmenu event.

Edit: To simulate the default click behavior on an <option> during a right mouse click, put this code in your event handler when handling right click:

clickedOption.parentNode.selectedIndex = clickedOption.index;



回答2:


If you are willing to use jQuery, you can simply use 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
   }
});

Of course you can use a fitting selector. This is great since that way, the right click is only serving as a left click on certain elements of your website. That way, it's still possible to use the mouse as expected most of the time (depending on your selectors).

EDIT: better example

<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>


来源:https://stackoverflow.com/questions/6988484/how-can-i-make-a-right-click-behave-as-a-left-click-for-the-purpose-of-selecting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!