使用jquery拖动时如何使元素跟随另一个元素?

时间:2014-06-20 06:02:00

标签: javascript jquery html5 drag-and-drop draggable

我需要在拖动时使元素跟随另一个元素,但是在动画中有延迟,类似于“Facebook的信使的聊天头”,你知道,Android上的气泡。

这是我的jQuery插件:

// Draggable plugin
(function($) {
$.fn.drag = function(options) {
    options = $.extend({
        handle: null,
        cursor: 'move',
        draggingClass: 'dragging',
        heads: null
    }, options);

    var $handle = this,
        $drag = this;

    if( options.handle ) {
        $handle = $(options.handle);
    }

    $handle
        .css('cursor', options.cursor)
        .on("mousedown", function(e) {
            var x = $drag.offset().left - e.pageX,
                y = $drag.offset().top - e.pageY,
                z = $drag.css('z-index');

            $drag.css('z-index', 100000);

            $(document.documentElement)
                .on('mousemove.drag', function(e) {
                    var chats = $($(options.heads).get().reverse());

                    chats.each(function(i) {
                        $(chats[i]).css({ left: $drag.position().left - (10*i)});
                        $(chats[i]).css({top: $drag.position().top});
                    });

                    $drag.offset({
                        left: x + e.pageX,
                        top: y + e.pageY
                    });
                })
                .one('mouseup', function() {
                    $(this).off('mousemove.drag');
                    $drag.css('z-index', z);

                    var window_width = $(window).width();
                    var window_height = $(window).height();
                    var head_wpostion = $(options.heads).position().left;
                    var head_hposition = $(options.heads).position().top;

                    if( head_wpostion > (window_width / 2) )
                    {
                      $(options.heads).animate({left: (window_width-40)+"px"}, 300 );
                      $(options.heads).animate({left: (window_width-50)+"px"}, 300 );
                    }
                    else
                    {
                      $(options.heads).animate({left: "-15px"}, 300 );
                      $(options.heads).animate({left: "-5px"}, 300 );
                    }

                    if( head_hposition > (window_height - 50) )
                    {
                      $(options.heads).animate({top: (window_height-75)+"px"}, 200 );
                      $(options.heads).animate({top: (window_height-65)+"px"}, 200 );
                    }

                    if( head_hposition < 0 )
                    {
                      $(options.heads).animate({top: "15px"}, 150 );
                      $(options.heads).animate({top: "5px"}, 150 );
                    }
                });

            // disable selection
            e.preventDefault();
        });
};
})(jQuery);

1 个答案:

答案 0 :(得分:0)

唯一可行的方法是将要拖动的元素放置在与可拖动元素相关的位置。