How to tell if mouse moved during .click()?

前端 未结 4 1121
半阙折子戏
半阙折子戏 2021-01-23 22:53

According to the jQuery documentation for .click(), the event is triggered only after this series of events:

  • The mouse button is depressed while the pointer is ins
相关标签:
4条回答
  • 2021-01-23 23:44

    Do you consider a mousedown and a mouseup event trigger to be a viable alternative? If the coordinates of the mousedown are the same as the coordinates for the mouseup, the cursor has not changed position during the click.

    0 讨论(0)
  • 2021-01-23 23:45

    I modified @adeneo's code a little bit, so it takes care of the problem where the user moves the cursor "just a little bit" and it should actually be interpreted as a click. I used eucledian distance for this. You could drop the Math.sqrt for better performance, but then you have to adjust the radiusLimit variable.

    var left = 0,
        top = 0,
        radiusLimit = 5;
    
    $(element).on({
      mousedown: function(event) {
        left = event.pageX;
        top = event.pageY;
      },
      mouseup: function(event) {
        var deltaX = event.pageX - left;
        var deltaY = event.pageY - top;
        var euclidean = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    
        if (euclidean < radiusLimit) {
          console.log("this is a click.");
        }
      }
    });
    
    0 讨论(0)
  • 2021-01-23 23:54

    Keep track of the mouse position between mousedown and mouseup to see it the mouse pointer moved. You should probably add a little margin of error, like a few pixels every way, but below is a simplified example :

    var left  = 0,
        top   = 0;    
    
    $(element).on({
        mousedown: function(e) {
            left  = e.pageX;
            top   = e.pageY;
        },
        mouseup: function(e) {
            if (left != e.pageX || top != e.pageY) {
                alert(' OMG, it moved ! ');
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-23 23:55

    No, there is no such event, as that would be almost completely useless. It's very common that the mouse moves slightly while clicking even if the user didn't intend that, especially with a regular mouse where the button for clicking is located on the moused itself.

    Get the mouse coordinates in the mousedown and mouseup events, and act on the mouseup event depending on how far the mouse has moved.

    0 讨论(0)
提交回复
热议问题