我在 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查看成功將元素放置到其原始位置的函數。
正確地將可拖動元素恢復到其起始位置
蕭十郎
2023-12-14 15:25:25