When the drag event is fired in Firefox, the mouse coordinates are (0,0)

Viewed 23

I want to make a mobile phone theme effect on the browser, and I need to make the icon get the current mouse position when it is dragged. In order to judge whether the user wants to insert the currently dragged icon at the mouse position, but I use the event object (@drag($event) ) of the drag method in the Firefox browser to get the mouse coordinates (event. pageX, event.screenX), it shows (0,0) or a fixed value, but when I use Google Chrome, the above situation does not occur, it immediately gives me the coordinates of the current mouse. Regarding the problem of the value of layerXY in the picture, this value will only be updated once at the beginning of dragging, and will not change at the rest of the time. Since I personally like to use the Firefox browser, I want to solve this problem, can anyone help me? Or give me some other suggestions to implement this function (my English is not very good, from google translate)

1 Answers

You could update the mouse coordinate on a global variable when the mouse moves so that it will be ready for you when mouse is down.

let drag = document.querySelector('.note');
var pageX, pageY

drag.onmousedown = function(e) {
  let coord = getCoord(drag);
  let shiftX = pageX - coord.left;
  let shiftY = pageY - coord.top;
  drag.style.position = 'absolute';
  document.body.appendChild(drag);
  moveNote(e);
  drag.style.zIndex = 1000;

  function moveNote(e) {
    drag.style.left = pageX - shiftX + 'px';
    drag.style.top = pageY - shiftY + 'px';

    var position = {
      x: drag.style.left,
      y: drag.style.top
    }
  }
  document.onmousemove = function(e) {
    moveNote(e);
  };
  drag.onmouseup = function() {
    document.onmousemove = null;
    drag.onmouseup = null;
  };

}

function getCoord(elem) {
  let main = elem.getBoundingClientRect();
  return {
    top: main.top,
    left: main.left
  };
}

window.onload = function() {

  document.addEventListener("mousemove", function(e) {
    pageX = e.pageX
    pageY = e.pageY
  });

  drag.style.position = 'absolute';
  document.body.appendChild(drag);
  drag.style.display = 'block'
}
.note {
  width: 50px;
  height: 50px;
  background: red;
  display: none;
}
<div class="note"></div>

Related