【问题标题】:Changing the image source of a droppable with a draggable image使用可拖动图像更改可放置对象的图像源
【发布时间】:2014-11-24 10:34:14
【问题描述】:

我有一个<div>,其中包含三个“可放置”类的图像。该表格有四行,图片位于最后一个 <td> 元素内。

HTML 如下所示:

<div id="box_container">
  <img id="empty_box1" class="droppable" src="images/tom.png" />
  <img id="empty_box2" class="droppable" src="images/tom.png" />
  <img id="empty_box3" class="droppable" src="images/tom.png" />
</div>

<td><img id="" class="draggable" src="images/image1.png" /></td>

下图是布局的样子:

表格中的图像可以拖到表格上方的空框中。这些框由空白图像组成,我希望该图像的来源更改为已放入空框中的图像。

下面是我现阶段的代码:

$(document).ready(function () {
  $(".draggable").draggable({
    revert: true,
    snap: ".droppable",
    snapMode: "inner"
  });
  $("#tabellen").tablesorter();
  $(".droppable").droppable({
    accept: ".draggable",
    drop: function () {
        console.log(this);
        var new_pic = $('.draggable').attr('src');
        $(this)
            .attr('src', new_pic)
            .attr('width', 150)
            .attr('height', 150)
            .addClass('zoomable');
    }
  });
});

【问题讨论】:

  • 那么问题是什么?
  • 问题是如何让空框中的图像变成被拖放到上面的图像。
  • 欢迎来到 stackOverflow。如果您提供使用 JS 所需的样板 HTML 和 CSS,而不仅仅是图像,它将极大地帮助那些试图帮助您的人。事实上,我们不知道#draggable1#draggable2 等是什么,或者你的 HTML 结构。请编辑您的问题并使用更多信息进行更新。顺便说一句,除非初始化选项不同,否则您应该真正使用一个通用类,而不是用id 一个一个地初始化每个可拖动对象。
  • 我尝试从我的 HTML 中添加一些 sn-ps,并对 jQuery 进行了一些调整。希望这对我更有帮助,因为我将非常感谢任何有关我的问题的帮助。
  • @Rinusu 答案(将 droppables 源设置为 ui.draggable.attr("src"))有帮助吗?

标签: jquery jquery-ui draggable jquery-ui-draggable jquery-ui-droppable


【解决方案1】:

drop 事件回调中,您可以通过第二个参数(通常称为ui)的draggable 属性访问拖放的可拖动元素。您可以复制它的源到 droppable,如下所示:

$(".draggable").draggable({
  helper: "clone",
  revert: "invalid"
});
$(".droppable").droppable({
  drop: function(event, ui) {
    $(this).attr("src", ui.draggable.attr("src"));
  }
});
img {
  width: 100px;
  height: 100px;
}
.draggable {
  background: hotpink;
  float: left;
}
.droppable {
  float: right;
  background: dodgerblue;
}
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<img class="draggable" src="http://i49.tinypic.com/28vepvr.jpg" />
<img class="droppable" src="" alt="Drop Here!" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2021-06-16
    • 1970-01-01
    • 2011-08-13
    • 2014-08-15
    • 1970-01-01
    相关资源
    最近更新 更多