本文介绍了在jquery中拖动元素时显示自定义图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using JQuery UI for drag and drop tree nodes and its working fine.

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

I need to improvise it in terms of much more user interactive, When i drag any element it shows the same element name, you can see in the image (Test 3 I've dragged to down).

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

But my requirement is when I drag any tree node it should show the image specified, instead of same text. Is it possible?

我的可拖动功能如下,我需要做些什么改变才能达到要求。

My draggable function as follows, what changes i need to do to achieve the requirement.

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

推荐答案

正如所建议的那样,你可以做一个特别的帮手。以下是一个工作示例:

As was suggested, you can make a special helper. Here is a working example: 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 里面,这样我就可以更轻松地定位它了。由于它被视为链接,我禁止点击事件。

The function creates a div and sets the background, nice and tidy. I then added the text to a span inside, so I could position it easier. Since it is seen as a link, I suppressed the click event.

这篇关于在jquery中拖动元素时显示自定义图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:50