Jquery UI Draggable: Align helper to mouse positio

2019-03-24 06:22发布

问题:

With jQuery I have a draggable element. It's a div with a size of 200 x 40. Of course the user can start dragging this div by clicking at variuos positions in the div. What I want is when the startdrag event happens, the helper (clone) div will always be aligned to the cursor the same way, no matter where in the div the user started dragging.

So after the mousedown the helper's top and left values need to be the same as the mouses x and y. I've tried this using this coffeescript code:

onStartDrag: ( e, ui ) =>
    ui.helper.css
        left: e.clientX
        top: e.clientY

    console.log( e )

But it doesn't work and my guess is that this is happening because the values I put in are directly overwritten by the draggable plugin because of mouse movement..

Any ideas?

回答1:

After trying Amar's answer and realizing that it screws up interactions with droppable, I dug deeper, and found that there is an option specifically to support this called cursorAt.

$('blah').draggable
  helper: ->
    ... custom helper ...
  cursorAt:
    top: 5
    left: 5

This places the top-left corner of the helper 5 pixels above and to the left of the cursor, and interacts correctly with droppable.

http://api.jqueryui.com/draggable/#option-cursorAt

And let's give credit where credit is due. Thanks, jquery-ui mailing list archives!

https://groups.google.com/forum/#!topic/jquery-ui/Evb94G_QvNw



回答2:

Try setting like this,

       start: function (event, ui) {
                $(ui.helper).css("margin-left", event.clientX - $(event.target).offset().left);
                $(ui.helper).css("margin-top", event.clientY - $(event.target).offset().top);
            }

Take a look at this jqFAQ.com , it will be more helpful for you.



回答3:

I've found a fix for this and it's very easy, if you are using the sortable plugin you can fix the helper position like this:

sort: function(e, ui) {
    $(".ui-sortable-handle.ui-sortable-helper").css({'top':e.pageY});
}


回答4:

This did the trick for me:

appendTo: 'body'

Like so:

$(this).draggable({
    helper: "clone",
    cursor: "move",
    appendTo: 'body'
});