Nice programing

jQuery : mousemove 이벤트 중 눌린 마우스 버튼 감지

nicepro 2020. 11. 8. 11:06
반응형

jQuery : mousemove 이벤트 중 눌린 마우스 버튼 감지


jQuery에서 mousemove 이벤트 중에 사용자가 누르는 마우스 버튼을 감지하려고 시도했지만 모호한 결과가 나타납니다.

no button pressed:      e.which = 1   e.button = 0
left button pressed:    e.which = 1   e.button = 0
middle button pressed:  e.which = 2   e.button = 1
right button pressed:   e.which = 3   e.button = 2

암호:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

<input id="whichkey" value="type something">
<div id="log"></div>
<script>$('#whichkey').bind('mousemove',function(e){ 
  $('#log').html(e.which + ' : ' +  e.button );
});  </script>

</body>
</html>

왼쪽 마우스 버튼을 누른 것과 버튼이 전혀없는 것을 어떻게 구분할 수 있습니까?


마우스 왼쪽 버튼의 상태를 추적하는 약간의 코드를 작성할 수 있으며 약간의 기능을 사용하여 이벤트에서 이벤트 변수를 사전 처리 할 수 ​​있습니다 mousemove.

LMB을의 상태를 추적, 바인딩에 대한 문서 수준에 이벤트로 유지하려면 mousedownmouseup대한 체크를 e.which설정 또는 플래그를 지 웁니다.

전처리 tweakMouseMoveEvent()는 내 코드 함수에 의해 수행됩니다 . IE 버전 <9를 지원하려면 마우스 버튼이 창 밖에서 해제되었는지 확인하고 그럴 경우 플래그를 지워야합니다. 그런 다음 전달 된 이벤트 변수를 변경할 수 있습니다. 경우 e.which원래 1 (아무 버튼이나 LMB)와 왼쪽 버튼의 현재 상태를 누르지 단지 설정 없었다 e.which0당신의 나머지 부분에 있음을, 사용 mousemove이벤트가 어떤 버튼에 확인을 누르면.

mousemove내 예제 핸들러는 현재 이벤트 변수를 전달하는 tweak 함수를 호출 한 다음 값을 출력합니다 e.which.

$(function() {
    var leftButtonDown = false;
    $(document).mousedown(function(e){
        // Left mouse button was pressed, set flag
        if(e.which === 1) leftButtonDown = true;
    });
    $(document).mouseup(function(e){
        // Left mouse button was released, clear flag
        if(e.which === 1) leftButtonDown = false;
    });

    function tweakMouseMoveEvent(e){
        // Check from jQuery UI for IE versions < 9
        if ($.browser.msie && !e.button && !(document.documentMode >= 9)) {
            leftButtonDown = false;
        }

        // If left button is not set, set which to 0
        // This indicates no buttons pressed
        if(e.which === 1 && !leftButtonDown) e.which = 0;
    }

    $(document).mousemove(function(e) {
        // Call the tweak function to check for LMB and set correct e.which
        tweakMouseMoveEvent(e);

        $('body').text('which: ' + e.which);
    });
});

여기에서 라이브 데모를보십시오 : http://jsfiddle.net/G5Xr2/


Most browsers (except Safari) *) now support the MouseEvent.buttons property (note: plural "buttons"), which is 1 when the left mouse button is pressed:

$('#whichkey').bind('mousemove', function(e) { 
    $('#log').html('Pressed: ' + e.buttons);
});

https://jsfiddle.net/pdz2nzon/2

*) The world is moving forward:
https://webkit.org/blog/8016/release-notes-for-safari-technology-preview-43/
https://trac.webkit.org/changeset/223264/webkit/


jQuery normalizes the which value so it will work across all browsers. I bet if you run your script you will find different e.button values.


For some reason, when binding to mousemove event, the event.which property is set to 1 if left button or none is pressed.

I changed to mousedown event and it worked Ok:

  • left: 1
  • middle: 2
  • right: 3

Here's a working example: http://jsfiddle.net/marcosfromero/RrXbX/

The jQuery code is:

$('p').mousedown(function(event) {
    console.log(event.which);
    $('#button').text(event.which);
});

Those variables are updated when the mousedown event (amongst others) fires; you're seeing the value that remains from that event. Note that they are properties of that event, not of the mouse itself:

Description: For key or button events, this attribute indicates the specific button or key that was pressed.

There is no value for "no button press", because the mousedown event will never fire to indicate that there's no button being pressed.

You'll have to keep your own global [boolean] variable and toggle it on/off on mousedown/mouseup.

  • This will only work if the browser window had focus when the button was pressed, which means a focus-switch between the user depressing the mouse button and your mousemove event firing will prevent this from working properly. However, there's really not much you can do about that.

As of the date, the following works on Firefox 47, Chrome 54 and Safari 10.

$('#whichkey').bind('mousemove',function(e){
    if (e.buttons & 1 || (e.buttons === undefined && e.which == 1)) {
        $('#log').html('left button pressed');
    } else if (e.buttons & 2 || (e.buttons === undefined && e.which == 3)) {
        $('#log').html('right button pressed');
    } else {
        $('#log').html('no button pressed');
    }
});

For users looking for similar solution but without the use of JQuery, here is a way of how I solved my problem:

    canvas.addEventListener("mousemove", updatePosition_mouseNtouch);

    function updatePosition_mouseNtouch (evt) {
      // IF mouse is down THEN set button press flag
      if(evt.which === 1)
        leftButtonDown = true;
      // If you need to detect other buttons, then make this here
      // ... else if(evt.which === 2) middleButtonDown = true;
      // ... else if(evt.which === 3) rightButtonDown = true;
      // IF no mouse button is pressed THEN reset press flag(s)
      else
        leftButtonDown = false;

      if (leftButtonDown) {
        /* do some stuff */
      }
    }

I hope this is usefull to someone seeking an answer.

참고URL : https://stackoverflow.com/questions/4065992/jquery-detecting-pressed-mouse-button-during-mousemove-event

반응형