在使用 jQuery UI 可拖动和可放置元素时,如何在放置时更改拖放元素?我正在尝试将一个 DIV 拖到另一个可排序的 DIV.在放置时,我想更改放置的 DIV 上的类并更改其 innerHTML 内容.
When using jQuery UI draggables and droppables, how do you change the dragged-and-dropped element on drop? I am trying to drag one DIV to another sortable DIV. On drop, I'd like to change the classes on the dropped DIV and change its innerHTML content.
阅读各种 StackOverflow 问题后,我的代码如下所示:
After reading various StackOverflow questions, my code looks like this:
$(".column").droppable({
accept: '.element-dragging',
drop: function(event, ui) {
if ($(ui.draggable).hasClass("elemtxt")) {
$(ui.draggable).replaceWith('<div class="element element-txt">This text box has been added!</div>');
}
}
})
它不适合我.:-(
我的代码的完整副本位于 http://www.marteki.com/jquery/bugkilling.php.
A full copy of my code is located at http://www.marteki.com/jquery/bugkilling.php.
从您提供的链接中获取完整的 javascript 代码,您可以进行如下更改以使其工作:
Taking the full javascript code from the link you gave, you can change it as follows to make it work:
$(function() {
$(".elementbar div").draggable({
connectToSortable: '.column',
cursor: 'move',
cursorAt: { top: 0, left: 0 },
helper: 'clone',
revert: 'invalid'
});
$(".elementbar div, .elementbar div img").disableSelection();
$(".column").sortable({
connectWith: '.column',
cursor: 'move',
cursorAt: { top: 0, left: 0 },
placeholder: 'ui-sortable-placeholder',
tolerance: 'pointer',
stop: function(event, ui) {
if (ui.item.hasClass("elemtxt")) {
ui.item.replaceWith('<div class="element element-txt">This text box has been added!</div>');
}
}
});
$(".element").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all");
});
有几个问题:
接受
正确的内容..sortable
和.droppable
你最终会触发奇怪的双重事件.无论如何,这都是不必要的,因为您可以有效地从 sortable 的事件中获取 drop 事件,因为您已将它与可拖动对象链接.accept
ing the right content..sortable
& .droppable
you end up with weird double events firing. This is unnecessary anyway, since you can effectively grab the drop event from sortable's events given that you've linked it with the draggable.还有一点需要注意 - 使用 sortable 的 receive
事件而不是 stop
会更好(因为每次任何排序停止和接收时都会触发 stop当您将新项目放入排序列表时会特别触发),但它无法正常工作,因为 item
尚未添加到可排序列表中,所以您没有能够在那个时候改变它.它在停止时可以正常工作,因为其他可排序项目都没有 elemtxt
类.
One other thing to note - it would have been nicer to use the sortable's receive
event instead of stop
(since stop gets fired every time any sorting stops & receive is specifically there to fire when you drop a new item into the sort list), but it doesn't work properly because the item
hasn't yet been added to the sortable list, so you aren't able to change it at that point. It works ok on stop simply because none of the other sortable items have the elemtxt
class.
这篇关于使用 jQuery UI 拖放:更改拖放的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!