检测 X 像素的 mouseMove

Detect mouseMove of X pixels

我试图在光标位置移动 X 个像素(比如 100 像素)时触发一个事件。因此,对于光标在 X 或 Y 方向上每移动 100px,我都会触发一个事件。每移动 100 像素,这应该会继续。

我已经成功检测到 'current' 光标的 X 和 Y 位置,并设置了像素阈值,但我正在努力解决其余部分的数学问题。有人可以帮忙吗?

$(window).on('mousemove', function(e){

    // Vars
    var cursorX = e.clientX;
    var cursorY = e.clientY;
    var cursorThreshold = 100;

    ... detect every 100px movement here...

});

要跟踪定义步骤的鼠标移动,您只需保存最后一个位置,然后检查光标在一个方向上的移动是否超过阈值。这是一个例子:

// Vars
var lastCursorX     = null;
var lastCursorY     = null;
var cursorThreshold = 100;

$(window).on('mousemove', function(e){

    //set start-points
    if (lastCursorX === null)
      lastCursorX = e.clientX;
      
    if (lastCursorY === null)
      lastCursorY = e.clientY;
    
    //check for move left
    if (e.clientX <= lastCursorX - cursorThreshold) {
    
      lastCursorX = e.clientX;
      console.log (cursorThreshold + 'px moved left');
    
    }

    //check for move right
    if (e.clientX >= lastCursorX + cursorThreshold) {
    
      lastCursorX = e.clientX;
      console.log (cursorThreshold + 'px moved right');
    
    }
    
    //check for move up
    if (e.clientY <= lastCursorY - cursorThreshold) {
    
      lastCursorY = e.clientY;
      console.log (cursorThreshold + 'px moved up');
    
    }

    //check for move down
    if (e.clientY >= lastCursorY + cursorThreshold) {
    
      lastCursorY = e.clientY;
      console.log (cursorThreshold + 'px moved down');
    
    }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您需要跟踪旧的光标位置。然后你可以使用勾股定理计算距离:

totalDistance += Math.sqrt(Math.pow(oldCursorY - cursorY, 2) + Math.pow(oldCursorX - cursorX, 2))

这适用于任何方向。

示例:

注意:与 @wayneOS 的方法(我的 +1)不同,我不跟踪方向。
这是一个相当简约的实现。

var totalDistance = 0;
var oldCursorX, oldCursorY;

$(window).on("mousemove", function(e){
    var cursorThreshold = 100;
    
    if (oldCursorX) totalDistance += Math.sqrt(Math.pow(oldCursorY - e.clientY, 2) + Math.pow(oldCursorX - e.clientX, 2));
    if (totalDistance >= cursorThreshold){
        console.log("Mouse moved 100px!");
        totalDistance = 0;
    }
    
    oldCursorX = e.clientX;
    oldCursorY = e.clientY;
});
.d {
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 100px 100px 0 0;
    border-color: #e54646 transparent transparent transparent;
}
.s { display: flex; }
.p1 { margin-left: 100px; }
.p2 { margin-right: 20px; padding-top: 20px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="p1">100px X</p>
<div class="s">
    <p class="p2">100px Y</p>
    <div class="d"></div>
</div>