2011-08-05 70 views
1

我有一個返回鼠標事件位置的函數。奇怪的鼠標事件位置問題

// returns the xy point where the mouse event was occured. 
function getXY(ev){ 
var xypoint = new Point(); 
if (ev.layerX || ev.layerY) { // Firefox 
    xypoint.x = ev.layerX; 
    xypoint.y = ev.layerY; 
} else if (ev.offsetX || ev.offsetX == 0) { // Opera 
    xypoint.x = ev.offsetX; 
    xypoint.y = ev.offsetY; 
} 
return xypoint; 
} 

我捕獲鼠標事件以在html5畫布上執行繪圖。有時我會爲xy獲得-ve值。當我使用螢火蟲調試應用程序時,我變得非常奇怪的行爲。例如,如果我用條件(xypoint.x < 0 || xypoint.y < 0)將此斷點放在此函數的第4行,它會停在斷點處,我可以看到layer.x,layer.y是積極正確的。但xypoint.x或xypoint.y是負數。如果我使用firbug控制檯重新分配值,我會在xypoint中獲得正確的值。任何人都可以解釋我發生了什麼事。

上述工作正常,如果我移動鼠標與正常速度。如果我以非常快的速度移動鼠標,我會得到這種行爲。

謝謝

回答

0

處理鼠標位置是Canvas的絕對痛苦。你必須做很多調整。我用這個,裏面有一些小失誤,但即使我在我的應用程序使用的拖放和下降的div作品:

getCurrentMousePosition = function(e) { 
    // Take mouse position, subtract element position to get relative position. 
    if (document.layers) { 
    xMousePos = e.pageX; 
    yMousePos = e.pageY; 
    xMousePosMax = window.innerWidth+window.pageXOffset; 
    yMousePosMax = window.innerHeight+window.pageYOffset; 
    } else if (document.all) { 
    xMousePos = window.event.x+document.body.scrollLeft; 
    yMousePos = window.event.y+document.body.scrollTop; 
    xMousePosMax = document.body.clientWidth+document.body.scrollLeft; 
    yMousePosMax = document.body.clientHeight+document.body.scrollTop; 
    } else if (document.getElementById) { 
    xMousePos = e.pageX; 
    yMousePos = e.pageY; 
    xMousePosMax = window.innerWidth+window.pageXOffset; 
    yMousePosMax = window.innerHeight+window.pageYOffset; 
    } 
    elPos = getElementPosition(document.getElementById("cvs")); 
    xMousePos = xMousePos - elPos.left; 
    yMousePos = yMousePos - elPos.top; 
    return {x: xMousePos, y: yMousePos}; 
} 

getElementPosition = function(el) { 
    var _x = 0, 
     _y = 0; 

    if(document.body.style.marginLeft == "" && document.body.style.marginRight == "") { 
    _x += (window.innerWidth - document.body.offsetWidth)/2; 
    } 

    if(el.offsetParent != null) while(1) { 
    _x += el.offsetLeft; 
    _y += el.offsetTop; 
    if(!el.offsetParent) break; 
    el = el.offsetParent; 
    } else if(el.x || el.y) { 
    if(el.x) _x = el.x; 
    if(el.y) _y = el.y; 
    } 
    return { top: _y, left: _x }; 
} 

這個故事的寓意?您需要計算畫布的偏移量以獲得正確的結果。您從事件中捕獲XY,其中有一個相對於窗口XY未捕獲的偏移量。合理?

+0

謝謝你的回覆,但它沒有解決我的問題。我的獲取XY位置的函數給了我正確的結果,問題在於有時從事件到變量的賦值沒有發生。 –

+0

啊,我明白了。你在兩個瀏覽器中都失去了作業嗎? – stslavik