在Firefox中触发拖动事件时,鼠标坐标为(0,0)



我想在浏览器上制作一个手机主题效果,我需要让图标在拖动时获得当前的鼠标位置。为了判断用户是否想在鼠标位置插入当前拖动的图标,但我在Firefox浏览器中使用拖动方法的事件对象(@drag($event((来获取鼠标坐标(event.pageX,event.screenX(,它显示(0,0(或固定值,但当我使用Google Chrome时,不会出现上述情况,它会立即给我当前鼠标的坐标。关于图片中layerXY的值的问题,该值在拖动开始时只会更新一次,在其余时间不会更改。由于我个人喜欢使用Firefox浏览器,我想解决这个问题,有人能帮我吗?或者给我一些其他的建议来实现这个功能(我的英语不是很好,来自谷歌翻译(

您可以在鼠标移动时更新全局变量上的鼠标坐标,以便在鼠标放下时为您做好准备。

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>

最新更新