本文介绍了Jquery`detach()`和`append`到新的父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态网页,我使用Jquerydraggable& droppable。

我试图将一个元素从一个父级移动到另一个。

I have a dynamic webpage where i use Jquery "draggable" & "droppable".
I'm trying to move one element from one "parent" to another.

当我做控制台.log我可以看到元素有一个新的父。

但是当我以后添加更多的HTML内容到DOM,元素不会移动与它的新父。它会卡在文档偏移位置。

我如何解决这个问题?

When i do "console.log" i can see that the element has a new parent.
But When i later on add more HTML content to the DOM, the element won't move with it's new parent. It's stuck to the "document" offset position.
How can i solve this?

FIDDLE

JS

      //Make elements Draggable
  $('.elementsDiv').draggable({
    revert: 'invalid',
  });
  var flakUpId = $('#1').attr('id');

  $('#btnAddDropZone').on('click', function() {
    flakUpId++;
    var flakUp = "<div class='flakUp'>DropZone " + flakUpId + " </div>";
    $('#dropZones').prepend(flakUp);
  })

  $('.flakUp, .flakDown').droppable({
    accept: '.elementsDiv',
    drop: function(event, ui) {
      var droppable = $(this);
      var draggable = ui.draggable;

      //Detach element from DOM
      draggable.detach();

      //Append element to droped position and into new parent?
      draggable.css({
        "left": ui.offset.left,
        "top": ui.offset.top,
        "position": "absolute"
      }).appendTo(droppable);
    },
  });


推荐答案

如何?

//Make elements Draggable
$('.elementsDiv').draggable({
  revert: 'invalid',
});
var flakUpId = $('#1').attr('id');

$('#btnAddDropZone').on('click', function() {
  flakUpId++;
  var flakUp = "<div class='flakUp'>DropZone " + flakUpId + " </div>";
  $('#dropZones').prepend(flakUp);

  registDroppable();

  $(".flakUp .elementsDiv").each(function(e) {
    $(this).css({"top": $(this).offset().top+$(".flakUp").height()});
  });
})

function registDroppable() {
    $('.flakUp, .flakDown').droppable({
    accept: '.elementsDiv',
    drop: function(event, ui) {
      var droppable = $(this);
      var draggable = ui.draggable;
      // Move draggable into droppable

      draggable.css({
        "left": ui.offset.left,
        "top": ui.offset.top,
        "position": "absolute"
      }).appendTo(droppable);
    },
  });
}
registDroppable();

这篇关于Jquery`detach()`和`append`到新的父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 13:37