在 jquery 中拖动元素时显示自定义图像

Show custom image when drag an element in jquery

我正在使用 JQuery UI 来拖放树节点并且它工作正常。

我需要在更多的用户交互方面即兴创作,当我拖动任何元素时它显示相同的元素名称,你可以在图像中看到(测试 3 我已经拖到下面)。

但我的要求是,当我拖动任何树节点时,它应该显示指定的图像,而不是相同的文本。可能吗?

我的draggable函数如下,需要做哪些改动才能达到要求

 $("li a").draggable({
        revert: "invalid",
        containment: "document",
        helper: "clone",
        cursor: "move",
        start: function(event, ui) {
            var draggedId = event.target.id;
        }
 }); 

为此使用 helper: function() 。它允许使用辅助元素来拖动显示。

helper: function() {
        return $("<div></div>").append($( '<img src="http://www.flooringvillage.co.uk/ekmps/shops/flooringvillage/images/request-a-sample--547-p.jpg" width="100">' ));
    }

Working Demo

Reference

按照建议,你可以做一个特殊的帮手。这是一个工作示例:https://jsfiddle.net/Twisty/ja1635y9/

HTML

<ul class="tree">
  <li class="top">Liabilities
    <ul>
      <li class="sub"><a href="https://www.eliteediting.com/images/get-free-instant-quote-small-button-hover.png">Test 0</a></li>
      <li class="sub"><a href="https://www.eliteediting.com/images/get-free-instant-quote-small-button-hover.png">Test 1</a></li>
      <li class="sub"><a href="https://www.eliteediting.com/images/get-free-instant-quote-small-button-hover.png">Test 2</a></li>
      <li class="sub"><a href="https://www.eliteediting.com/images/get-free-instant-quote-small-button-hover.png">Test 3</a></li>
    </ul>
  </li>
</ul>

JQuery

$(function() {
  $(".sub a").draggable({
    revert: "invalid",
    containment: "document",
    helper: function(e, ui) {
      var $img = $(this).attr("href");
      var $d = $("<div>");
      $d.css({
        "width": "250px",
        "height": "48px",
        "background-image": "url(" + $img + ")",
        "background-repeat": "no-repeat",
        "padding": "12px 0"
      });
      var $text = $("<span>" + $(this).text() + "</span>");
      $text.css({
        "display": "block",
        "color": "#fff",
        "text-align": "center",
        "width": "100%"
      });
      $d.append($text);
      return $d;
    },
    cursor: "move",
    start: function(event, ui) {
      var draggedId = event.target.id;
    }
  }).click(function(e) {
    e.preventDefault();
  });
});

函数创建一个div并设置背景,漂亮整洁。然后我将文本添加到一个 span 里面,这样我就可以更容易地定位它。由于它被视为 link,我抑制了 click 事件。