Custom helper for jQuery UI Draggable

早过忘川 提交于 2019-11-29 01:23:13

First your way of calling draggable is faulty. The expected parameter is an object literal, not a function.

this is the currently dragged element in the helper function.

Having the following html

<ul>
  <li><div class="name">Name</div> <span>12-12-2011</span></li>
  <li><div class="name">Another name</div> <span>12-12-2011</span></li>
</ul>

You can do this:

$('ul li').draggable({
    helper: function() {
        //debugger;
        return $("<div></div>").append($(this).find('.name').clone());
    }
});

Note: I have added class to the <div> representing the name for the sake of selecting it but you can find any other way to do so.

Here's a jsfiddle for you to check.

OK, with a quick test the following will work....

$("ul li").draggable({
    helper: function() {
        return $("<div>hello</div>");
    } });

notice you do not pass a function as a draggable parameter. Also, I have added "hello" to the example so the helper DIV actually contains something.

EDIT: This seems to prevent the element being dropped, hmmm...

A FIX: Not pretty, but this works, maybe it can give some ideas for improvement...

var remember;
$("ul li").draggable({
    helper: 'original',
    start: function(e, ui) {
        remember = $(this).html();
        $(this).html("<div>hello</div>");
    },
    stop: function(e, ui) {
        $(this).html(remember);
    }
});

Example Here

If you don't like the idea of the "remember" variable it seems to be ok to add a custom option to the draggable object that can hold the original html...

$("ul li").draggable({
    helper: 'original',
    start: function(e, ui) {
        $(this).draggable("option", "olddata", $(this).html());
        $(this).html("<div>hello</div>");
    },
    stop: function(e, ui) {
        $(this).html($(this).draggable("option", "olddata"));
    }
});

One possible solution is

Fiddle: http://jsfiddle.net/SWbse/

   $(document).ready(function() {
      $("ul li").draggable({
         helper: 'clone',
         start: function(event, ui){
            ui.helper.children('span').remove();
         }    
     });
   });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!