【问题标题】:How can I use javascript timing to control on mouse stop and on mouse move events如何使用 javascript 计时来控制鼠标停止和鼠标移动事件
【发布时间】:2010-09-18 04:09:10
【问题描述】:

所以我在 aspx 页面上有一个控件(地图)。我想编写一些 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”永远不会被停止清除。我错过了什么?

【问题讨论】:

    标签: javascript timeout onmousemove


    【解决方案1】:

    这是一个棘手的问题。一点点修修补补导致了这个:

    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 会反复触发,并且您每次都开始新的超时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多