Is right click a Javascript event?

后端 未结 18 2324
南笙
南笙 2020-11-22 10:02

Is right click a Javascript event? If so, how do I use it?

18条回答
  •  萌比男神i
    2020-11-22 10:41

    The following code is using jQuery to generate a custom rightclick event based on the default mousedown and mouseup events. It considers the following points:

    • trigger on mouseup
    • trigger only when pressed mousedown on the same element before
    • this code especially also works in JFX Webview (since the contextmenu event is not triggered there)
    • it does NOT trigger when the contextmenu key on the keyboard is pressed (like the solution with the on('contextmenu', ...) does

    $(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');
    });
    
    

提交回复
热议问题