2016-03-04 66 views
2

我正在使用JQuery UI拖放树节点并且工作正常。我需要根据更多的用户交互来即兴创作它,当我拖动任何显示相同元素名称的元素时,您可以在图像中看到(测试3我拖动到了下方)。在jQuery中拖动元素时显示自定义图像

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

我的可拖动功能如下,我需要做什么改变来实现要求。

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

See the image here

+0

你可以创建一个jsfiddle http://jsfiddle.net? – guest271314

+0

这是可能的,我会建议使用助手并将图像附加到助手。 – Twisty

+0

另外,为了提供帮助,我们需要看到更多的代码或一个小例子,如@ guest271314所提到的。 – Twisty

回答

2

至于有人建议,你可以做一个特殊的帮手。这是一个工作示例: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,所以我可以更容易地定位。由于它被视为一个链接,我压制了click事件。

2

使用助手:函数()来。它允许使用助手元素来拖动显示。

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

相关问题