是否有可能获得鼠标移动的负坐标

时间:2016-07-28 09:27:04

标签: javascript

我正在使用此功能来获取鼠标位置。但我也从日志中收到负值。我无法找到此函数将返回负值的方案。

function mouseMoveTracker(event) {
    var dot, eventDoc, doc, body, pageX, pageY;
    event = event || window.event;

    if (event.pageX == null && event.clientX != null) {
        eventDoc = event.target && event.target.ownerDocument || document;
        doc = eventDoc.documentElement;
        body = eventDoc.body;

        event.pageX = 
            event.clientX + 
            (doc && doc.scrollLeft || body &&   body.scrollLeft || 0) -
            (doc && doc.clientLeft || body && body.clientLeft || 0);

        event.pageY =
            event.clientY +
            (doc && doc.scrollTop || body && body.scrollTop || 0) -
            (doc && doc.clientTop || body && body.clientTop || 0);
    }

    var mm = {x: event.pageX, y: event.pageY, time: Date.now()};
}

1 个答案:

答案 0 :(得分:0)

试试这个

var x;
var y;
if (e.pageX || e.pageY) { 
  x = e.pageX;
  y = e.pageY;
}
else { 
  x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
  y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
} 
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;

希望它有所帮助!