如何获得鼠标坐标

时间:2018-03-22 05:19:31

标签: javascript html

我想获得相对于img的鼠标坐标,但是当鼠标位于rectangle上时,它会返回相对于它的坐标。 如何正确获取坐标?

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <style>
        .rectangle {
            border: 1px solid #FF0000;
            position: absolute;
            left:100px;
            top:100px;
            width:100px;
            height:200px;
        }
    </style>
    <title></title>
</head>
<body>
    <div id="coords"></div>
    <div id="canvas">
        <img id="img" src="img.jpg" />
        <div class="rectangle" id="rectangle"></div>
    </div>
    <script>
        var canvas = document.getElementById('canvas');
        canvas.onmousemove = function (event) {
            var x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("img").offsetLeft;
            var y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("img").offsetTop;
            console.log(event.target.id)
            var coords = "X coords:" + x + ", Y coords: " + y;
            document.getElementById("coords").innerHTML = coords;
        }
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以将代码用作:

&#13;
&#13;
(function() {
  var canvas = document.getElementById('canvas');
  canvas.onmousemove = handleMouseMove;
  // document.onmousemove = handleMouseMove;
  function handleMouseMove(event) {
    var dot, eventDoc, doc, body, pageX, pageY;

    event = event || window.event; // IE-ism

    // If pageX/Y aren't available and clientX/Y are,
    // calculate pageX/Y - logic taken from jQuery.
    // (This is to support old IE)
    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);
    }

    // Use event.pageX / event.pageY here
    var coords = "X coords:" + event.pageX + ", Y coords: " + event.pageY;
    document.getElementById("coords").innerHTML = coords;
  }
})();
&#13;
.rectangle {
  border: 1px solid #FF0000;
  position: absolute;
  left: 100px;
  top: 100px;
  width: 100px;
  height: 200px;
}
&#13;
<div id="coords"></div>
<div id="canvas">
  <img id="img" src="img.jpg" />
  <div class="rectangle" id="rectangle"></div>
</div>
&#13;
&#13;
&#13;

感谢 @ T.J。克劳德