2008-10-20 42 views
6

Vì vậy, tôi có một điều khiển (bản đồ) trên trang aspx. Tôi muốn viết một số javascript để onload thiết lập như sau:Làm cách nào tôi có thể sử dụng thời gian javascript để kiểm soát thời gian dừng chuột và các sự kiện di chuyển chuột

  1. khi chuột dừng trên kiểm soát = một số mã

  2. khi di chuyển chuột = một số mã (nhưng chỉ khi di chuyển dài hơn 250 triệu giây)

này hoạt động để kích hoạt mã trên dừng lại và sau đó trên di chuyển ...

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

Nhưng tôi không thể tìm ra cách giới thiệu độ trễ vào mã di chuyển. Tôi nghĩ rằng tôi đã có nó với điều này ...

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

Nhưng nó không hoạt động như tôi nghĩ. Việc di chuyển "thread2" không bao giờ bị xóa bởi điểm dừng. Tôi đang thiếu gì?

Trả lời

6

Đó là một điều khó khăn. Một chút mày mò dẫn đến điều này:

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

    })(); 

}; 

Lý do mã của bạn không hoạt động là cháy MouseMove nhiều lần trong khi chuột đang chuyển động và bạn đang bắt đầu timeouts mới mỗi lần.

+0

cảm ơn bạn, đã làm việc như một sự quyến rũ. Bạn đá! – mrjrdnthms

Các vấn đề liên quan