问题
I have an HTML5 application which utilizes drag and drop. Essentially the user can drag an image from a "drawer" onto a canvas to create a larger image. I want the elements to drop in the place where they were release. I have this working in all browsers except Firefox.
On the drop event, I am using the following to get the coordinates of the mouse, and calculate the position of the dropped image within the canvas.
var top = evt.originalEvent.offsetX;
var left = evt.originalEvent.offsetY;
The issue is, this property is not available in FF. Is there any other way to get this? Without it, I can't see how to possible drag and move elements within FF.
Note: I am not using the canvas element. I am dropping images to a div. Not sure if that matters.
回答1:
Try this in firefox..
var X = event.layerX - $(event.target).position().left;
var Y = event.layerY - $(event.target).position().top;
回答2:
I tried using layerX and layerY but mysteriously they were different from same values in Chrome.
Then I realized that on a Retina display Firefox setDragImage won't take the scale into account.
In other words, calling setDragImage(div, 10, 10) would place the cursor at 5px; 5px point.
Ridiculous, isn't it?
var originalEvent = e.originalEvent,
offsetX = originalEvent.offsetX,
offsetY = originalEvent.offsetY;
if (_.isUndefined(offsetX) || _.isUndefined(offsetY)) {
// Firefox doesn't take scale into account so we need to compensate for it
offsetX = originalEvent.layerX * (window.devicePixelRatio || 1);
offsetY = originalEvent.layerY * (window.devicePixelRatio || 1);
}
originalEvent.dataTransfer.setDragImage(el, offsetX, offsetY);
回答3:
I tried Kathirvans answer above but it didnt work for me. The magic potion for my page was...
var x = e.originalEvent.pageX - $(this).offset().left;
var y = e.originalEvent.pageY - $(this).offset().top;
来源:https://stackoverflow.com/questions/13435690/html5-drag-and-drop-mouse-position-in-firefox