我正在使用 JQuery UI 拖放树节点,并且工作正常。
我需要在更多的用户交互方面即兴发挥,当我拖动任何元素时,它会显示相同的元素名称,您可以在图像中看到(我已向下拖动的测试 3)。
但我的要求是,当我拖动任何树节点时,它应该显示指定的图像,而不是相同的文本。可能吗?
我的可拖动功能如下,我需要做哪些更改才能达到要求。
$("li a").draggable({
revert: "invalid",
containment: "document",
helper: "clone",
cursor: "move",
start: function(event, ui) {
var draggedId = event.target.id;
}
});
最佳答案
正如建议的,你可以做一个特殊的 helper 。这是一个工作示例: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
事件。
关于jquery - 在 jquery 中拖动元素时显示自定义图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790360/