jQuery UI: Drag and clone from original div, but keep clones

前端 未结 4 1952
故里飘歌
故里飘歌 2020-12-15 04:37

I have a div, which has jQuery UI Draggable applied. What I want to do, is click and drag that, and create a clone that is kept in the dom and not removed when dropped.

4条回答
  •  无人及你
    2020-12-15 05:20

    Here is how I got it working: PS: 'marker' is the object to drag and 'map' is the destination container.

    $(document).ready(function() {
        //source flag whether the drag is on the marker tool template
        var template = 0;
        //variable index
        var j = 0;
        $(".marker").draggable({
            helper: 'clone',
            snap: '.map',
            start: function(event, ui) {
                //set the marker tool template
                template = 1;
            }
        });
        $(".map").droppable({
            accept: ".marker",
            drop: function(event, ui) {
                $(this).find('.map').remove();
                var item = $(ui.helper);
                var objectid = item.attr('id');
                //if the drag is on the marker tool template
                if (template == 1) {
                    var cloned = $(item.clone());
                    cloned.attr('id', 'marker' + j++);
                    objectid = cloned.attr('id');
                    cloned.draggable({
                        containment: '.map',
                        cursor: 'move',
                        snap: '.map',
                        start: function(event, ui) {
                            //Reset the drag source flag 
                            template = 0;
                        }
                    });
                    cloned.bind("contextmenu", function(e) {
                        cloned.remove();
                        return false;
                    });
                    $(this).append(cloned);
                }
                i++;
                var offsetXPos = parseInt(ui.offset.left - $(this).offset().left);
                var offsetYPos = parseInt(ui.offset.top - $(this).offset().top);
                alert("Dragged " + objectid + " to (" + offsetXPos + "," + offsetYPos + ")");
            }
        });
    });
    

提交回复
热议问题