IT

자바 스크립트 이벤트를 마우스 오른쪽 버튼으로 클릭합니까?

lottoking 2020. 6. 16. 08:00
반응형

자바 스크립트 이벤트를 마우스 오른쪽 버튼으로 클릭합니까?


자바 스크립트 이벤트를 마우스 오른쪽 버튼으로 클릭합니까? 그렇다면 어떻게 사용합니까?


다른 사람들이 언급했듯이 오른쪽 마우스 버튼은 일반적인 마우스 이벤트 (mousedown, mouseup, click)를 통해 감지 할 수 있습니다 . 그러나 마우스 오른쪽 버튼 클릭 메뉴가 표시 될 때 발생하는 이벤트를 찾으려면 잘못된 위치를 찾고있는 것입니다. 오른쪽 클릭 / 컨텍스트 메뉴는 키보드 (Windows 및 일부 Linux에서는 Shift + F10 또는 컨텍스트 메뉴 키)를 통해 액세스 할 수도 있습니다. 이 상황에서 찾고있는 이벤트는 oncontextmenu다음과 같습니다.

window.oncontextmenu = function ()
{
    showCustomMenu();
    return false;     // cancel default menu
}

마우스 이벤트 자체는 브라우저가 이벤트 처리 기능에서 액세스 할 수있는 이벤트 객체로 속성을 설정합니다.

document.body.onclick = function (e) {
    var isRightMB;
    e = e || window.event;

    if ("which" in e)  // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
        isRightMB = e.which == 3; 
    else if ("button" in e)  // IE, Opera 
        isRightMB = e.button == 2; 

    alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!");
} 

window.oncontextmenu-MDC


다음 jQuery 코드를 살펴보십시오.

$("#myId").mousedown(function(ev){
      if(ev.which == 3)
      {
            alert("Right mouse button clicked on element with id myId");
      }
});

의 가치 which는 다음과 같습니다.

  • 왼쪽 버튼의 경우 1
  • 중간 버튼의 경우 2
  • 오른쪽 버튼은 3

다음과 같은 이벤트를 사용할 수 있습니다 window.oncontextmenu.

window.oncontextmenu = function () {
  alert('Right Click')
}
<h1>Please Right Click here!</h1>


w3c는 오른쪽 클릭이 클릭 이벤트에 의해 감지 될 수 있다고 말하지만 onClick은 일반적인 브라우저에서 오른쪽 클릭을 통해 트리거되지 않습니다.

실제로 마우스 오른쪽 버튼을 클릭하면 onMouseDown onMouseUp 및 onContextMenu 만 트리거됩니다.

따라서 "onContextMenu"를 오른쪽 클릭 이벤트로 간주 할 수 있습니다. HTML5.0 표준입니다.


아니요, "onmousedown"이벤트에서 어떤 마우스 버튼이 사용되었는지 감지 할 수 있으며 "오른쪽 클릭"인지 확인할 수 있습니다.


다음 코드는 jQuery를 사용 rightclick하여 기본 mousedown이벤트를 기반으로 사용자 정의 이벤트 를 생성 mouseup합니다. 다음 사항을 고려합니다.

  • 마우스 업시 트리거
  • 전에 동일한 요소에서 마우스 다운을 눌렀을 때만 트리거
  • 이 코드는 특히 JFX Webview에서도 작동합니다 ( contextmenu이벤트가 트리거되지 않기 때문에)
  • 키보드에서의 ContextMenu 키이 (가)와 솔루션처럼 (누를 때 트리거하지 않습니다 on('contextmenu', ...)않습니다

$(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');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testButton">Rightclick me</button>


예-그렇습니다!

function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}

예, oncontextmenu가 가장 좋은 대안 일 수 있지만 마우스를 누르면 작동하지만 마우스를 누르면 클릭이 발생합니다.

다른 관련 질문은 수동 타이머 확인을 제외하고는 지원되지 않는 두 번 클릭에 대한 질문이었습니다. 왼손잡이 마우스 입력 (버튼 반전)을 지원해야하는 경우 오른쪽 더블 클릭을 원할 수있는 이유 중 하나입니다. 브라우저 구현은 사용 가능한 입력 장치를 어떻게 사용해야하는지에 대해 많은 가정을하는 것 같습니다.


Easiest way to get right click done is using

 $('classx').on('contextmenu', function (event) {

 });

However this is not cross browser solution, browsers behave differently for this event especially firefox and IE. I would recommend below for a cross browser solution

$('classx').on('mousedown', function (event) {
    var keycode = ( event.keyCode ? event.keyCode : event.which );
    if (keycode === 3) {
       //your right click code goes here      
    }
});

If you want to detect right mouse click, you shouldn't use MouseEvent.which property as it is non-standard and there's large incompatibility among browsers. (see MDN) You should instead use MouseEvent.button. It returns a number representing a given button:

  • 0: Main button pressed, usually the left button or the un-initialized state
  • 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
  • 2: Secondary button pressed, usually the right button
  • 3: Fourth button, typically the Browser Back button
  • 4: Fifth button, typically the Browser Forward button

MouseEvent.button handles more input types than just standard mouse:

Buttons may be configured differently to the standard "left to right" layout. A mouse configured for left-handed use may have the button actions reversed. Some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values.

Reference:

  1. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  2. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

That is the easiest way to fire it, and it works on all browsers except application webviews like ( CefSharp Chromium etc ... ). I hope my code will help you and good luck!

const contentToRightClick=document.querySelector("div#contentToRightClick");

//const contentToRightClick=window; //If you want to add it into the whole document

contentToRightClick.oncontextmenu=function(e){
  e=(e||window.event);
  e.preventDefault();
  console.log(e);
  
  return false; //Remove it if you want to keep the default contextmenu 
}
div#contentToRightClick{
  background-color: #eee;
  border: 1px solid rgba(0,0,0,.2);
  overflow: hidden;
  padding: 20px;
  height: 150px;
}
<div id="contentToRightClick">Right click on the box !</div>


Handle event using jQuery library

$(window).on("contextmenu", function(e)
{
   alert("Right click");
})

If You want to call the function while right click event means we can use following

 <html lang="en" oncontextmenu="func(); return false;">
 </html>

<script>
function func(){
alert("Yes");
}
</script>

This is worked with me

if (evt.xa.which == 3) 
{
    alert("Right mouse clicked");
}

To handle right click from the mouse, you can use the 'oncontextmenu' event. Below is an example:

 document.body.oncontextmenu=function(event) {
     alert(" Right click! ");
 };

the above code alerts some text when right click is pressed. If you do not want the default menu of the browser to appear, you can add return false; At the end of the content of the function. Thanks.


Yes, its a javascript mousedown event. There is a jQuery plugin too to do it

참고URL : https://stackoverflow.com/questions/2405771/is-right-click-a-javascript-event

반응형