2016-03-23 13 views
0

マウス入力時にトリガーされるコードブロックがあります。私はまた、マウスの動きが止まったことを検出するコードブロックを持っています。マウスが停止した後のトリガーコード

入力したオブジェクト内でマウスの移動が停止した場合にのみ、マウスセンターコードを実行してください。

// 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); 
} 
+0

が、これは動作しません... "最高" を定義するのに役立ちますか? – chazsolo

+0

マウスが停止したときの検出が機能します。しかし、マウスが停止していない限り、最初のブロックのコードを実行したくありません。私はどのように2つを組み合わせるか分からない。 – MarioD

+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を:あなたが欲しいの期間にidleWait変数を変更することができます

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) 

、(この例では2秒)

jsfiddle Example

は、私はあなただけの小さな変更を加える必要があります、それはあなたのために働く:)

+0

お返事いただきありがとうございます。私はそれを標準的な項目で動作させることができましたが、上に貼り付けた最初のコードブロックにそれを組み込む際に問題があります。私はこれをバニラJSにもっと慣れ親しむ方法としても使用していますので、jQueryから離れていきたいと思います。 – MarioD

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); 
}); 

希望これは

関連する問題