简体   繁体   中英

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

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.

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;

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM