我試圖通過拖動實現頁面panorate。在我的實現中,在用戶釋放鼠標按鈕後,頁面會移動一段時間,例如在Google地圖中拖動地圖。現在我想避免這種效果,當用戶釋放按鈕時鼠標不再移動。問題是,我只是無法弄清楚在觸發事件時鼠標是否真的移動。如何檢測mouseup被觸發時鼠標是否在移動?
現在我試圖通過計算拖動速度來解決這個問題,然後將速度與預先設定的「靈敏度」進行比較,該靈敏度在大多數情況下都有效,但有時會失敗。
簡化示例jsFiddle。當用小提琴演奏時,請使用FF中的中鍵,可拖動的div「粘」到左按鈕。
僞代碼:
AniMove = function (doc, element, sensitivity, panspeed, duration) {
var mouseDown = function (e) {
sTime = new Date();
originalX = mouseX = e.clientX;
originalY = mouseY = e.clientY;
/* addEventListeners mousemove & mouseup for document */
return;
},
mouseMove = function (e) {
/* Setting new position for #square + new mouseX & Y */
return;
},
mouseUp = function() {
var dc = 1;
/* removeEventListeners mousemove & mouseup */
eTime = new Date();
vX = Math.round((50 * panspeed) * (originalX - mouseX)/(eTime - sTime));
vY = Math.round((50 * panspeed) * (originalY - mouseY)/(eTime - sTime));
// Check whether mouse is moving or not,
// now checking the speed against sensitivity, which is not reliable
if (Math.abs(vX) < sensitivity){vX = 0;}
if (Math.abs(vY) < sensitivity){vY = 0;}
for (n = 0; n < dur; n++, dc += 0.001) {
vX = Math.round(vX * dec/dc);
vY = Math.round(vY * dec/dc);
delay[n] = setTimeout(endDrag(n, vX, vY), n * 50);
}
return;
},
endDrag = function (n, vX, vY) {
/* Setting new position for #square */
return;
},
dec = 1 - 120/duration;
panspeed *= -0.01;
duration /= 50;
element.addEventListener('mousedown', mouseDown, false);
}
drag = new AniMove(document, document.getElementById('square'), 20, 100, 500);
那麼,它甚至有可能,如果鼠標在這種情況下移動或不檢測?也許我需要一個不同的方法來完成這項任務?
謝謝,現在它工作!想到10毫秒的伎倆。工作小提琴:http://jsfiddle.net/cww55/7/ – Teemu