[英]How can I use javascript timing to control on mouse stop and on mouse move events
所以我在aspx頁面上有一個控件(一張地圖)。 我想寫一些javascript來onload設置如下:
當鼠標停在控制=某些代碼時
當鼠標移動=某些代碼時(但僅當移動時間超過250毫秒時)
這可以觸發代碼停止然后移動...
function setupmousemovement() {
var map1 = document.getElementById('Map_Panel');
var map = document.getElementById('Map1');
map1.onmousemove = (function() {
var onmousestop = function() {
//code to do on stop
}, thread;
return function() {
//code to do on mouse move
clearTimeout(thread);
thread = setTimeout(onmousestop, 25);
};
})();
};
但我無法弄清楚如何在移動代碼中引入延遲。 我以為我有這個......
function setupmousemovement() {
var map1 = document.getElementById('Map_Panel');
var map = document.getElementById('Map1');
map1.onmousemove = (function() {
var onmousestop = function() {
//code to do on stop
clearTimeout(thread2);
}, thread;
return function() {
thread2 = setTimeout("code to do on mouse move", 250);
clearTimeout(thread);
thread = setTimeout(onmousestop, 25);
};
})();
};
但它並沒有像我想象的那樣表現。 移動“thread2”永遠不會被停止清除。 我錯過了什么?
這是一個棘手的問題。 一點點的修補導致了這個:
function setupmousemovement() {
var map1 = document.getElementById('Map_Panel');
map1.onmousemove = (function() {
var timer,
timer250,
onmousestop = function() {
// code to do on stop
clearTimeout( timer250 ); // I'm assuming we don't want this to happen if mouse stopped
timer = null; // this needs to be falsy next mousemove start
};
return function() {
if (!timer) {
// code to do on start
timer250 = setTimeout(function () { // you can replace this with whatever
// code to do when 250 millis have passed
}, 250 );
}
// we are still moving, or this is our first time here...
clearTimeout( timer ); // remove active end timer
timer = setTimeout( onmousestop, 25 ); // delay the stopping action another 25 millis
};
})();
};
你的代碼不起作用的原因是當鼠標移動時你會反復觸發mousemove並且你每次都會開始新的超時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.