当前位置:  开发笔记 > 编程语言 > 正文

如何使用javascript计时来控制鼠标停止和鼠标移动事件

如何解决《如何使用javascript计时来控制鼠标停止和鼠标移动事件》经验,为你挑选了1个好方法。

所以我在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"永远不会被停止清除.我错过了什么?



1> Borgar..:

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

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并且你每次都会开始新的超时.

推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有