2013-02-25 69 views
10

怎麼可能與一個事件監聽來檢測何時mousemove已經完成如何檢測?當鼠標移動已停止

document.AddEventListener('mousemove', startInteractionTimer, false); 

function startInteractionTimer(){ 
    clearInterval(touchInterval); 
    touchInterval = setInterval(noAction, 6000); 
} 

我要立即啓動功能startInteractionTimer鼠標移動已經結束,我想趕上那之後。在上面的代碼示例中,如果移動鼠標,它將開始。

感謝

編輯:好吧,我回答我自己的問題和上面的腳本 - ^就好了。

+0

沒有你的例子正是這樣做 - 如果鼠標沒有移動一段時間,它調用'noAction'?當光標已停止(有沒有停事件'mousemove'如何來檢測?這隻能如果是在結合'mousedown'和'mouseup'如果例如用於拖動檢測) – 2013-02-25 12:25:53

+0

MouseMove事件觸發。所以,你可以檢測是否光標不動一段時間,做自己想做 – Sergio 2013-02-25 12:28:02

+0

沒有什麼,我的例子中觸發事件,如果鼠標移動!不是在鼠標移動停止之後。 – supersize 2013-02-25 12:28:21

回答

6

你總是可以做出一個自定義事件:

(function ($) { 
    var timeout; 
    $(document).on('mousemove', function (event) { 
     if (timeout !== undefined) { 
      window.clearTimeout(timeout); 
     } 
     timeout = window.setTimeout(function() { 
      // trigger the new event on event.target, so that it can bubble appropriately 
      $(event.target).trigger('mousemoveend'); 
     }, 100); 
    }); 
}(jQuery)); 

現在你可以只是這樣做:

$('#my-el').on('mousemoveend', function() { 
    ... 
}); 

編輯:

而且,與其他jQuery的事件一致性:

(function ($) { 
    $.fn.mousemoveend = function (cb) { 
     return this.on('mousemoveend', cb); 
    }); 
}(jQuery)); 

現在,您可以:

$('#my-el').mousemoveend(fn); 
5

你可以嘗試設置/清除超時僅在偵測到移動鼠標結束...

var x; 
document.addEventListener('mousemove', function() { 
    if (x) clearTimeout(x); 
    x = setTimeout(startInteractionTimer, 200); 
}, false); 

多久要等待由你。我不知道你要多久才能說是「鼠標移動結束」

例子:http://jsfiddle.net/jeffshaver/ZjHD6/

3

這裏是另一個自定義事件的解決方案,但沒有jQuery的。它創建了一個名爲mousestop的事件,將鼠標指針位於元素上被觸發。它會像其他鼠標事件一樣冒泡。

所以一旦你有一段代碼在內,你可以添加事件偵聽器的任何元素與addEventListener('mousestop', fn)

(function (mouseStopDelay) { 
 
    var timeout; 
 
    document.addEventListener('mousemove', function (e) { 
 
     clearTimeout(timeout); 
 
     timeout = setTimeout(function() { 
 
      var event = new CustomEvent("mousestop", { 
 
       detail: { 
 
        clientX: e.clientX, 
 
        clientY: e.clientY 
 
       }, 
 
       bubbles: true, 
 
       cancelable: true 
 
      }); 
 
      e.target.dispatchEvent(event); 
 
     }, mouseStopDelay); 
 
    }); 
 
}(1000)); 
 

 
// Example use 
 
document.getElementById('link').addEventListener('mousestop', function(e) { 
 
    console.log('You stopped your mouse while on the link'); 
 
    console.log('Mouse coordinates are: ', e.detail.clientX, e.detail.clientY); 
 
    // The event will bubble up to parent elements. 
 
});
<h1>Title</h1> 
 
<div> 
 
    content content<br> 
 
    <a id="link" href="#">stop your mouse over this link for 1 second</a><br> 
 
    content content content 
 
</div>

+0

工作非常感謝,在鉻上檢查 – Buddhi 2016-12-09 11:59:45

+0

很高興聽到它對你有用;-) – trincot 2016-12-09 12:00:52

相關問題