使用jQuery UI Draggable拖放纯HTML?

时间:2016-12-15 15:04:25

标签: javascript jquery html jquery-ui drag-and-drop

如何将HTML内容拖到"画布"?

我想有一个简单的按钮列表(可拖动的项目),我可以拖放一个项目。

我想要一个简单的按钮列表,但是当拖放到"画布上时#34;我希望它为每个按钮填充不同的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');

但是还没有找到一个很好的方法来放弃&#34;插入HTML&#34;进入画布而不是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 个答案:

答案 0 :(得分:1)

使用以下功能将新文本添加到拖动的项目中。 它会为每个拖动项添加它所拥有的属性。 data-insert-html

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

编辑:我原谅只定位拖动区域。我修改了我的代码。

相关问题