gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:20:39 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于javascript - 如何使用 javascript 计时来控制鼠标停止和鼠标移动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/219322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com