gpt4 book ai didi

jquery - 如何使用 Draggable 和 Droppable 交换 2 个项目?

转载 作者:行者123 更新时间:2023-12-01 02:43:04 27 4
gpt4 key购买 nike

问题

我有 4 张图片。用户可以将它们拖放到另一个列表中并更改图像的顺序。目标是用户选择图像的顺序。问题是当这些图像相互放置时我无法交换它们。

HTML

<ul id="choices">
<li><img src="http://placehold.it/200x200&text=1" /></li>
<li><img src="http://placehold.it/200x200&text=2" /></li>
<li><img src="http://placehold.it/200x200&text=3" /></li>
<li><img src="http://placehold.it/200x200&text=4" /></li>
</ul>

<ul id="answers">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>

jQuery
(function ($) {

$("#choices li img").draggable({
revert: true,
zIndex: 10,
snap: "#answers li",
snapMode: "inner",
snapTolerance: 40
});

$("#answers li").droppable({
drop: function (event, ui) {
var dropped = ui.draggable;
var droppedOn = this;

if ($(droppedOn).children().length > 0) {
alert("I need to swap these");
}

$(dropped).detach().css({
top: 0,
left: 0
}).prependTo($(droppedOn));
}
});
})(jQuery);

CSS(不是很重要)

img {
display: block;
z-index: 3;
}
#choices, #answers {
display:block;
padding: 0;
margin: 0;
}
#choices li, #answers li {
display: inline-block;
height: 200px;
width: 200px;
margin: 10px;
background: #515151;
}
#answers li {
position: relative;
}

示例

http://jsfiddle.net/K6QNg/

最佳答案

我的解决方案可能不是最优雅的(也许有人可以提供更直观的东西?),但它似乎有效;)

fiddle :http://jsfiddle.net/W9Z46/14/

(function ($) {
var lastPlace;

$("#choises li img").draggable({
revert: true,
zIndex: 10,
snap: "#answers li",
snapMode: "inner",
snapTolerance: 40,
start: function (event, ui) {
lastPlace = $(this).parent();
}
});

$("#answers li").droppable({
drop: function (event, ui) {
var dropped = ui.draggable;
var droppedOn = this;

if ($(droppedOn).children().length > 0) {
$(droppedOn).children().detach().prependTo($(lastPlace));
}

$(dropped).detach().css({
top: 0,
left: 0
}).prependTo($(droppedOn));
}
});
})(jQuery);

如您所见,我只是将您开始拖动的位置保留在变量 lastPlace 中,稍后当您放下并检查某物是否存在时,您将其放置在您之前开始拖动的位置.

关于jquery - 如何使用 Draggable 和 Droppable 交换 2 个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20269976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com