我正在尝试将"template"(最初作为克隆)从“商店”拖到可放置的插槽中。此后,我希望能够将拖动的项目放入我想要的任何插槽中。 Draggables 设置如下:
$( ".template" ).draggable({
helper: "clone",
}
);
$( ".item" ).draggable();
我通过在第一次放置时用“item”类替换“template”类来解决事物重新克隆的问题,并在放置函数中从克隆元素切换到直接元素,如下所示:
$( ".template-slot" ).droppable({
accept: ".template, .item",
drop: function( event, ui ) {
if(ui.draggable.hasClass("template")) {
$(this).append(ui.draggable.clone())
// add item class
$(".template-slot .template").addClass("item");
// remove template class
$(".item").removeClass("ui-draggable template");
// expand to fit the slot
$(".item").addClass("expand-to-slot");
// make it draggable again
$(".item").draggable();
}
if(ui.draggable.hasClass("item")) {
$(this).append(ui.draggable);
}
}
});
第一次拖放工作正常。第二次拖放时出现问题。该元素可以拖动,但是当放下时,无论我拖动它的方向,它都会放置两倍远。例如,如果我将其向右拖动 50 像素,它就会向右拖动 100 像素。向上和向下等也是如此。
我怀疑这与偏移量的累积有关,但还没有弄清楚为什么这样做或如何修复它。
我在这里创建了一个 fiddle :https://jsfiddle.net/stefem1969/a86jmnxu/10/来显示问题。
希望有人能帮忙。
最佳答案
工作示例:https://jsfiddle.net/Twisty/fu83zq2y/11/
JavaScript
$(function() {
function makeDrag(obj, opt) {
if (obj.hasClass("ui-draggable")) {
obj.removeClass("ui-draggable");
obj.attr("style", "");
}
if (opt === undefined) {
opt = {};
}
obj.draggable(opt);
}
makeDrag($(".template, .item"), {
helper: "clone",
});
$(".template-slot").droppable({
accept: ".template, .item",
drop: function(event, ui) {
if (ui.draggable.hasClass("template")) {
console.log("it has the template class!");
var newItem = ui.draggable.clone();
newItem.toggleClass("template item");
newItem.addClass("expand-to-slot");
newItem.appendTo($(this));
makeDrag(newItem);
}
if (ui.draggable.hasClass("item")) {
console.log("it has the item class!")
var droppableOffset = $(this).offset();
console.log("droppableOffset: ", droppableOffset);
ui.draggable.attr("style", "").appendTo($(this));
}
}
});
$(".template-store, .thagomizer").droppable({
accept: ".item",
drop: function(event, ui) {
ui.draggable.remove();
}
});
});
draggable 的一部分是在移动时设置 top
和 left
。即使您将该项目附加到另一个元素,它仍然会具有这些元素。清除它可以帮助实现您正在寻找的目标。
makeDrag()
只是有助于多次执行相同的操作。
希望这有帮助。
关于javascript - 第二次拖动时可拖动的位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54562833/