How to connect onmousemove with onmousedown?

左心房为你撑大大i 提交于 2019-12-24 19:45:28

问题


I want to press the mouse button and move the cursor, showing the coordinates of the cursor while the button is pressed. When i stop clicking it should stop showing the coordinates.

Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
  <style>
    body {
      height: 3000px;
    }
  </style>
</head>
<body>
<script>
  (function() {
    "use strict";

    document.onmousedown = handleMouseDown;
    function handleMouseDown(event) {
      console.log("down")
    }

    document.onmousemove = handleMouseMove;
    function handleMouseMove(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 );
      }
      console.log("left: " + event.pageX + "px -- right: " + event.pageY + "px");
    }
  })();
</script>
</body>
</html>

Thank you in advance.


回答1:


Just attach/detach the mousemove handling function upon mousedown/mouseup events:

document.onmousedown = function () {
    document.onmousemove = handleMouseMove;
};
document.onmouseup = function () {
    document.onmousemove = null;
};

function handleMouseMove(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 );
  }
  console.log("left: " + event.pageX + "px -- right: " + event.pageY + "px");
}


来源:https://stackoverflow.com/questions/48903805/how-to-connect-onmousemove-with-onmousedown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!