鼠标停止后的触发代码

Trigger code after mouse has stopped

本文关键字:代码 鼠标      更新时间:2023-09-26

我有一个在鼠标输入时触发的代码块。我还有一个代码块,可以检测鼠标何时停止移动。

我希望mouseenter代码只在鼠标在输入的对象内停止移动时运行。

// Add events to each dot
for (var i = 0; i < dots.length; i++) {
  dots[i].addEventListener('mouseenter', function (event) {
    var target = event.target;
    // Add a class called moving when follow dot is in a transition
    followDot.classList.add('moving');
    targetsPosition[0] = target.style.left;
    targetsPosition[1] = target.style.top;
    // Detect if the dot is moving left or right
    if (followDot.style.left < targetsPosition[0]) {
      removeMovingClasses();
      followDot.classList.add('moving-right');
    } else if (followDot.style.left > targetsPosition[0]) {
      removeMovingClasses();
      followDot.classList.add('moving-left');
    }
    //
    followDot.style.left = targetsPosition[0];
  });
}

超时代码:

// Detect when the mouse has stopped
document.onmousemove = function(){
  clearTimeout(timeout);
  timeout = setTimeout(function () {
    // console.log('mouse stopped');
  }, 300);
}

试试这个解决方案,当鼠标在div for example上闲置特定时间时,可以触发事件。

HTML:

<h2>fire event when mouse is idle</h2>
<div id="sample">
</div>

CSS:

#sample {
    width:200px;
    height:200px;
    background: #aaa;
}

JavaScript:

idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
var $sample = $("#sample");
    $('*').bind('mousemove keydown scroll', function () {
        clearTimeout(idleTimer);
        if (idleState == true) { 
            // Reactivated event
            if($sample.is(":hover")) {
                            alert('mouse has moved again');
                        }
        }
        idleState = false;
        idleTimer = setTimeout(function () { 
            // Idle Event
            if($sample.is(":hover")) {
                            alert('mouse has stopped for two seconds');
                        }
            idleState = true; }, idleWait);
    });
    $("body").trigger("mousemove");
});
}) (jQuery)

您可以将idleWait变量更改为所需的周期(本例中为2秒)

jsfiddle示例

我希望它对你有效:)

一切看起来都很好,您只需要做一个小的更改。尝试将mousemove事件添加到您的目标区域,而不是文档(除非它是整个文档)。此外,您应该将您的第一个块包装在一个函数中,以便在鼠标停止时调用。

示例

function mouseHasStopped(){
//code in first block...
}
//adding an event listener to whatever element is entered . in this example i'm using "element" as our entered object ...
element.addEventListener("mousemove",function(){
    clearTimeout(timeout);
    timeout=setTimeout(mouseHasStopped,300);
});

希望这能帮助