Jquery UI Draggable:将辅助线对齐到鼠标位置

17

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

因此,在mousedown之后,helper的顶部和左侧值需要与鼠标的x和y相同。我尝试使用以下coffeescript代码:

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

    console.log( e )

但是它不起作用,我猜测这是因为我输入的值直接被draggable插件由于鼠标移动而覆盖了..

有什么想法吗?


你应该设置一个JSFiddle让我们看到发生了什么。 - A. Wolff
5个回答

39

在尝试了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


你是完全正确的!(http://jsfiddle.net/vLmN5/)这个内置方法比在start函数中自己实现要好。 - Tim Baas
谢谢,你真是救命恩人! - Abraham
我感激不尽。这个辅助元素的定位困扰了我很长时间。谢谢! - hyde

15

试着这样设置,

       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
差不多了!但是使用margin-left/top而不是left/top就可以完成任务。这是我的解决方法:marginLeft: e.clientX - $(e.target).offset().leftmarginTop: e.clientY - $(e.target).offset().top。如果您能编辑您的帖子,我会接受它。谢谢! - Tim Baas

0
我已经找到了解决方法,非常简单。如果您正在使用可排序插件,您可以像这样修复助手位置:
sort: function(e, ui) {
    $(".ui-sortable-handle.ui-sortable-helper").css({'top':e.pageY});
}

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'

-1
这对我很有帮助:
appendTo: 'body'
像这样:
$(this).draggable({
    helper: "clone",
    cursor: "move",
    appendTo: 'body'
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接