奇怪的鼠标事件位置问题



我有一个返回鼠标事件位置的函数。

// 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画布上的绘图。有时候,xypoint的值是- 5。当我使用firebug调试应用程序时,我得到了非常奇怪的行为。例如,如果我把断点放在这个函数的第4行,条件是(xypoint.x<0 || xypoint.y<0),它在断点处停止,我可以看到那个层。x,层。Y是正的,正确的。但xypoint。X或xypoint。Y是负的。如果我使用firbug控制台重新分配值,我将在xypoint中获得正确的值。谁能告诉我发生了什么事?

如果我以正常速度移动鼠标,上述工作正常。如果我以非常快的速度移动鼠标,我就会得到这种行为。

谢谢

使用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未被捕获的偏移量。有意义吗?

最新更新