gpt4 book ai didi

javascript - Jquery 克隆功能在拖放时创建重复的图像?

转载 作者:行者123 更新时间:2023-11-28 07:36:37 26 4
gpt4 key购买 nike

我正在使用 jQuery 开发一个拖放应用程序。

但是,我遇到的问题是,当我拖放图像时,它会重复图像。

我确实尝试像这样删除给定的类:ui.helper.removeClass("draggable");

但我仍然看到图像重复,并且我不明白是什么导致了此问题。

这是我的整个代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
#dvSource img
{
height: 100px;
width: 100px;
margin: 2px;
}
.draggable
{
filter: alpha(opacity=60);
opacity: 0.6;
}
.dropped
{
position: static !important;
}
#dvSource, #dvDest
{
border: 5px solid #ccc;
padding: 5px;
min-height: 100px;
width: 430px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.24/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet"
type="text/css" />
<script type="text/javascript">
$(function () {
$("#dvSource img").draggable({
revert: "invalid",
refreshPositions: true,
drag: function (event, ui) {
ui.helper.addClass("draggable");
},
stop: function (event, ui) {
ui.helper.removeClass("draggable");
var image = this.src.split("/")[this.src.split("/").length - 1];
if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) {
//alert(image + " dropped.");
}
else {
alert(image + " not dropped.");
}
}
});
$("#dvDest").droppable({
drop: function (event, ui) {
if ($("#dvDest img").length == 0) {
$("#dvDest").html("");

}
ui.helper.removeClass("draggable");
ui.draggable.addClass("dropped");
//$("#dvDest").append(ui.draggable).clone();
$("#dvDest").append($(ui.draggable).clone());






}
});
});
</script>
<div id="dvSource">
<img alt="" src="images/Chrysanthemum.jpg" />
<img alt="" src="images/Desert.jpg" />
<img alt="" src="images/Hydrangeas.jpg" />
<img alt="" src="images/Jellyfish.jpg" />
<img alt="" src="images/Koala.jpg" />
<img alt="" src="images/Lighthouse.jpg" />
<img alt="" src="images/Penguins.jpg" />
<img alt="" src="images/Tulips.jpg" />
</div>
<hr />
<div id="dvDest">
Drop here
</div>
</body>
</html>

有人可以就这个问题提出建议吗?

最佳答案

问题是函数在这里被调用两次:

if($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) {
....

jQuery 已经调用 drop 但您要手动再次调用它。这不是检查事件的正确方法,但它会再次调用该事件。只需删除 if...else 子句,您的代码就会像魅力一样工作!

您还将一个对象扭曲到 $() 中,但该对象也是一个 jquery 对象。你不需要这样做

// NOT $("#dvDest").append($(ui.draggable).clone());
$("#dvDest").append(ui.draggable.clone());

关于javascript - Jquery 克隆功能在拖放时创建重复的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526218/

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