2011-10-07 73 views
0

我目前正在研究一個腳本,該腳本允許用戶將裝飾圖像拖放到聖誕樹上進行裝飾。我正在使用jquery-ui將圖像顯示在側欄上,並可以在樹上拖動。它的工作,有點。出於某種原因,在將圖像拖動到樹上之後,您無法再移動它,並且無法在樹上創建另一個可拖動的圖像,因爲原始圖像不再可拖動。jQuery UI拖放不止一次

下面的代碼,我想出了:

$(document).ready(function() { 
$('[clickable]').click(function() { 
    if ($(this).attr('targets')) 
    { 
     $($(this).attr('targets')).css('background-image', 'url(' + $(this).attr('src') + ')'); 
    } 
}); 

$('[draggable]').each(function() { 
    $(this).css('z-index', '30'); 
    $(this).draggable({ 
    revert: \"invalid\" 
    //, zIndex: 999 
    , helper: 'clone' 
    , containment: '#panel' 
    , appendTo: '#' + $(this).attr('targets') 
    }); 
}); 

$('[droppable]').each(function() { 
    $(this).css('z-index', '-20'); 
    $(this).droppable({ 
     accept: '[targets=' + $(this).attr('id') + ']' 
     , drop: function (e, ui) { 
      $(this).append($(ui)); 
      $(ui).draggable({ 
       revert: \"invalid\" 
       //, zIndex: 999 
       , containment: '#top' 
       , appendTo: '#top'//'#' + $(this).attr('targets') 
       }); 
     } 
    }); 
}); 
}); 

和HTML:

<div id="drop_area" droppable="droppable"> 
     <div id="canvas" droppable="droppable"> 
      <div id="background" droppable="droppable"> 
       <div id="tree" droppable="droppable"> 

       </div> 
      </div> 
     </div> 

     <div id="selectors"> 
      <img src="./images/dressup/largepinkbow.png" draggable="draggable" targets="tree" /> 
     </div> 

    </div> 

回答

0

您已接近一些的這種錯誤的方式。相反,如果使用$ .each你可以做jQuery選擇.droppable和.draggable。

$('[draggable]').draggable({...}) 

而且你不應該重新實例你把每個UI元素的.draggable()插件。你所要做的就是爲它定義一次,然後在dom的剩餘時間內拖動它。

喜歡的東西:

$('[draggable]') 
.css('z-index', '30') 
.draggable({ 
    revert: "invalid" 
    //, zIndex: 999 
    , helper: 'clone' 
    , containment: '#panel' 
    , appendTo: '[droppable]' 
    }); 
}); 

$('[droppable]') 
    .css('z-index', '-20'); 
    .droppable({ 
     accept: '[draggable]' 
     , drop: function (e, ui) { 
      $(this).append($(ui)); 
     } 
    }); 
});