2016-12-15 115 views
1

如何將HTML內容拖到「畫布」上?使用jQuery UI Draggable拖放純HTML?

我想要一個簡單的按鈕列表(可拖動的項目),在那裏我可以拖放一個項目。

我想要一個簡單的按鈕列表,但是當拖放到「畫布」上時,我希望它爲每個按鈕填充不同的HTML。

我看到有人在可拖動項中使用參數,如「data-insert-html」。在這裏我已經看到人們使用基本的HTML,或者他們想要放入.mywrapper的html文件的路徑。

我試過不同的方法。這是最密切的,但是從我想去的地方還是有些英里是:

<div class="draggable" data-insert-html='<h1>Some HTML</h1>'> 
My button text 
</div> 
<div class="draggable" data-insert-html='<p>Some other content</p>'> 
My button #2 text 
</div> 

的JS:

我發現,我可以用它來獲取數據:

var insertingHTML = $(this).attr('data-insert-html'); 

但是還沒有找到一個好方法來將這個「insertedHTML」放入畫布中,而不是放入DIV的內容。

$(".draggable").draggable({ 
     connectToSortable: ".mywrapper", 
     helper: "clone", 
     helper: function(event) { 
      return "<div class='custom-helper'>Add '" + $(this).context.innerHTML + "' by letting it go on the yellow field.</div>"; 

     }, 
     // I have tried to use the STOP event. But the problem with it is that I can only drag one item ONCE to the canvas. I want infinite. 
     stop: function() { 

     // This gets the correct data from the draggable DIV 
     var insertingHTML = $(this).attr('data-insert-html'); 

     // BUT then I am lost. How do I add this to where the marker is? 
     event.originalEvent.dataTransfer.setData("Text",insertingHTML); 
     // test ended 
     }, 
     revert: "invalid", 
    }); 
    $().disableSelection(); 

這裏是一個小提琴玩: http://jsfiddle.net/Preben/pcawje7u/8/

你能不能幫我解決我的代碼?

謝謝:-)

回答

1

使用下面的函數添加新的文本被拖動的項目。 它爲每個被拖動的物品添加它所擁有的財產。 data-insert-html

stop: function() { 
     $('.mywrapper [data-insert-html]').each(function(){ 
      $(this).html($(this).attr('data-insert-html')); 
     }); 
     }, 

編輯,我忘記目標只有拖拽區域。我修復了我的代碼。

+0

奇怪的事情發生了:http://jsfiddle.net/Preben/pcawje7u/11/ – Preben

+0

你沒有更新你的小提琴。 :) –

+0

錯誤的鏈接。這裏我做了一些奇怪的事。給我一分鐘:-) – Preben