Jquery UI Draggable:将帮助器对齐鼠标位置

时间:2012-11-05 10:43:37

标签: javascript jquery coffeescript draggable

使用jQuery我有一个可拖动的元素。这是一个大小为200 x 40的div。 当然,用户可以通过单击div中的variuos位置来开始拖动此div。 我想要的是当startdrag事件发生时,无论用户开始拖动的div在哪里,助手(克隆)div总是以相同的方式与光标对齐。

因此,在mousedown之后,帮助者的顶部和左侧值必须与鼠标x和y相同。我用这个coffeescript代码试过这个:

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

    console.log( e )

但它不起作用,我的猜测是发生了这种情况,因为我放入的值由于鼠标移动而被可拖动插件直接覆盖..

有什么想法吗?

5 个答案:

答案 0 :(得分:38)

在尝试了Amar的回答并意识到它搞砸了与droppable的互动之后,我深入挖掘,发现有一个专门支持这个名为cursorAt的选项。

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

这会将帮助程序的左上角放置在光标上方和左侧5个像素处,并与droppable正确交互。

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

让我们在信用到期时给予信任。谢谢,jquery-ui邮件列表档案!

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

答案 1 :(得分:13)

尝试这样设置,

       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);
            }

看一下这个jqFAQ.com,它会对你有所帮助。

答案 2 :(得分:0)

我已经找到了解决这个问题的方法很容易,如果你使用的是可排序的插件,你可以像这样修复辅助位置:

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

答案 3 :(得分:0)

我同意@roverv。

这对我来说很好用。

Example of my icon following the mouse cursor after scrolling the page

$('.js-tire').draggable
      tolerance: 'fit',
      appendTo: 'body',
      cursor: 'move',
      cursorAt:
        top: 15,
        left: 18
      helper: (event) ->
        $('<div class="tire-icon"></div>').append($('<img src="/images/tyre_32_32.png" />'))
      start: (event, ui) ->
        if $(event.target).hasClass 'in-use'
          $('.js-send-to-maintenance-box').addClass 'is-highlighted'
        else
          $('.ui-droppable').addClass 'is-highlighted'
      stop: (event, ui) ->
        $('.ui-droppable')
          .removeClass 'is-highlighted'
          .removeClass 'is-dragover'

答案 4 :(得分:-1)

这对我有用:

appendTo:&#39; body&#39;

像这样:

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