我在 Rails 6 应用程序中使用InteractJs 库。我已经实现了它的拖放事件。
拖放功能运行良好。我面临的问题是,如果我将一个元素从拖放区中删除并将其放置到其原始(起始)位置,它就会定位在那里,但是如果我尝试再次拖动该元素,它会出现在前一个元素所在的位置上拖动结束而不是恢复到的位置,这是我要解决的问题
以下是我的事件代码
var dragMoveListener = function (event) {
var target, x, y;
target = event.target;
x = (parseFloat(target.getAttribute("data-x")) || 0) + event.dx;
y = (parseFloat(target.getAttribute("data-y")) || 0) + event.dy;
target.style.webkitTransform = target.style.transform =
"translate(" + x + "px, " + y + "px)";
target.setAttribute("data-x", x);
return target.setAttribute("data-y", y);
};
window.dragMoveListener = dragMoveListener;
interact('*[data-draggable="true"]').draggable({
inertia: false,
autoScroll: true,
onmove: dragMoveListener,
});
const restoreToOriginalPosition = (event) => {
// this restores the element to it's original position but the next time I attempt to drag it, it appears on the position where the previous dragging ended
event.relatedTarget.style.transform = "translate(0px, 0px)";
};
$(document).on("turbolinks:load", function () {
interact("#dropzone").dropzone({
accept: '*[data-draggable="true"]',
overlap: 0.75,
ondropactivate: function (event) {
// ...
},
ondrop: function (event) {
const product_id = event.relatedTarget.attributes["data-product-id"].value;
// my use case is to remove the element from DOM if it's dropped into the dropzone, otherwise restore to it's starting position
$(event.relatedTarget).remove();
addToCart(product_id); //it's definition is not relevant here
},
ondropdeactivate: function (event) {
restoreToOriginalPosition(event);
},
});
});
在ondrop事件侦听器中,我尝试将元素恢复到其在页面上的原始位置。restoreToOriginalPosition查看成功将元素放置到其原始位置的函数。
慕仙森
相关分类