http://jsfiddle.net/zander_pope/93n39bm8/
您好。你有我的jsfiddle。 我创建了一个插件,但我被卡住了。 如果不在它的drop元素上,我无法使拖动项返回其原始位置。如果我将它放在另一个drop元素上,它将转到它自己的drop元素,而不是转到它的原始位置。 请帮助我解决这个问题并指出正确的道路。 JS:
var height = $(window).height();
$("#draggable").height(height);
$("#droppable").height(height);
(function ($) {
$.fn.dnd = function (opt) {
opt = $.extend({
drop: "",
handle: "",
cursor: "move"
}, opt);
if (opt.handle === "") {
var $el = this;
var $le = opt.drop;
} else {
var $el = this.find(opt.handle);
var $le = this.find(opt.drop);
}
return $el.css('cursor', opt.cursor).on("mousedown", function (e) {
if (opt.handle === "") {
var $drag = $(this).addClass('drag');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('drag');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
$drag.css('z-index', 1000).parents().on("mousemove", function (e) {
$('.drag').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup", function () {
$(this).removeClass('drag').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup", function () {
if (!$le) {
$(this).css({
"left": "0",
"top": "0"
});
} else if ($le) {
$(this).removeClass('drag').css({
"left": "0",
"top": "40px",
"margin": "auto",
"width": "100%",
"text-align": "center"
}).removeAttr('id').appendTo($le);
}
});
};
})(jQuery);
(function ($) {
$.fn.rand = function (tree, childElem) {
return this.each(function () {
var $this = $(this);
if (tree) $this = $(this).find(tree);
var unsortedElems = $this.children(childElem);
var elems = unsortedElems.clone();
elems.sort(function () {
return (Math.round(Math.random()) - 0.5);
});
for (var i = 0; i < elems.length; i++)
unsortedElems.eq(i).replaceWith(elems[i]);
});
};
})(jQuery);
$("#draggable").rand();
$("#id1").dnd({
drop: "#drop1"
});
$("#id2").dnd({
drop: "#drop2"
});