2008-10-20 25 views
6

所以我有一個控制(一張地圖)在一個aspx頁面。我想要寫一些JavaScript來爲onload設置如下:我如何使用javascript時間來控制鼠標停止和鼠標移動事件

  1. 當鼠標控制停止=一些代碼

  2. 當鼠標移動=一些代碼(但只有當移動長於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」永遠不會被停止清除。我錯過了什麼?

回答

6

這是一個棘手的問題。修修補補的一點點,因此本:

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

    })(); 

}; 

的原因,你的代碼不起作用的是,鼠標移動大火反覆,而鼠標移動,你的每一次開始新的超時。

+0

謝謝你,工作就像一個魅力。你搖滾! – mrjrdnthms 2008-10-20 20:28:26