JavaScript 타이밍을 사용하여 마우스 정지 및 마우스 이동 이벤트를 제어하는 방법
-
03-07-2019 - |
문제
그래서 ASPX 페이지에 컨트롤 (맵)이 있습니다. Onload 설정을 위해 JavaScript를 작성하고 싶습니다.
마우스가 컨트롤에서 중지 될 때 = 일부 코드
마우스가 움직일 때 = 일부 코드 (그러나 이동이 250 mil 초 미만인 경우에만)
이것은 정지시 코드를 트리거 한 다음 움직일 때 ...
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);
};
})();
};
그러나 ON Move 코드에 지연을 도입하는 방법을 알 수 없습니다. 나는 이것으로 그것을 가지고 있다고 생각했다 ...
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);
};
})();
};
그러나 그것은 내가 생각했던 것처럼 행동하지 않습니다. On Move "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 화재가 반복적으로 화재되고 매번 새로운 타임 아웃을 시작하기 때문입니다.
제휴하지 않습니다 StackOverflow