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

前端 未结 4 1122
半阙折子戏
半阙折子戏 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: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.");
        }
      }
    });
    

提交回复
热议问题