可拖动的JS元素在按钮点击时没有重新进入



我有以下JS代码,我用它来移动屏幕上的东西,然后当我点击一个按钮,我想把所有东西移回原始元素加载的地方。为什么我下面的逻辑不起作用?我也试过减去gMouseDownOffsetXgMouseDownOffsetY,按钮仍然没有将图像转换回它开始的原点。

我知道这个按钮是有效的,因为它实际上改变了我设置的其他属性,但不改变位置。

$('#clickMe').click(function(){
$(#element).css({' transform : 'translate('+ -gMouseDownX + ')' });
$(#element).css({' transform : 'translate(' + -gMouseDownY + ')' });
});



let gMouseDownX = 0;
let gMouseDownY = 0;
let gMouseDownOffsetX = 0;
let gMouseDownOffsetY = 0;
function addListeners() {
document.getElementById('cursorImage').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp() {
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
gMouseDownX = e.clientX;
gMouseDownY = e.clientY;
var div = document.getElementById('cursorImage');
//The following block gets the X offset (the difference between where it starts and where it was clicked)
let leftPart = "";
if(!div.style.left)
leftPart+="0px";    //In case this was not defined as 0px explicitly.
else
leftPart = div.style.left;
let leftPos = leftPart.indexOf("px");
let leftNumString = leftPart.slice(0, leftPos); // Get the X value of the object.
gMouseDownOffsetX = gMouseDownX - parseInt(leftNumString,10);
//The following block gets the Y offset (the difference between where it starts and where it was clicked)
let topPart = "";
if(!div.style.top)
topPart+="0px";     //In case this was not defined as 0px explicitly.
else
topPart = div.style.top;
let topPos = topPart.indexOf("px");
let topNumString = topPart.slice(0, topPos);    // Get the Y value of the object.
gMouseDownOffsetY = gMouseDownY - parseInt(topNumString,10);
window.addEventListener('mousemove', divMove, true);
}
function divMove(e){
var div = document.getElementById('cursorImage');
div.style.position = 'absolute';
let topAmount = e.clientY - gMouseDownOffsetY;
div.style.top = topAmount + 'px';
let leftAmount = e.clientX - gMouseDownOffsetX;
div.style.left = leftAmount + 'px';
}
addListeners();

我发现通过设置top和left来移动您的位置。为什么不尝试直接将顶部和左侧的值设置为默认值呢?

更新:

试试这个:

$('#clickMe').click(function(){
$("#cursorImage").css({ left: 0, top: 0});
});

最新更新