鼠标停止后触发代码

时间:2016-03-23 20:23:59

标签: javascript dom mouse

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

我希望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);
}

2 个答案:

答案 0 :(得分:0)

尝试此解决方案,您可以在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 Example

我希望它适合你:)

答案 1 :(得分:0)

一切看起来都很好你只需做一个小改动。尝试将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);
});

希望这有帮助