【问题标题】:jQuery UI draggable: bind to object in mousemove event?jQuery UI 可拖动:在 mousemove 事件中绑定到对象?
【发布时间】:2016-05-08 06:53:30
【问题描述】:

我需要能够在mousemove 事件中动态地将 HTML 对象设置为 jQuery UI 可拖动对象;这是因为页面上的某些对象是动态创建的,光标下。

天真的方法不起作用(因为,我猜,draggable() 绑定到mousedown 事件)。有没有办法破解 jQuery UI 可拖动插件,所以我可以将它分配给 mousemove 上的元素并立即开始拖动它?

提前谢谢你。

【问题讨论】:

  • 如果你说的是在不停止当前鼠标移动的情况下拖动新元素,我相信它已经被问过很多次了,这几乎是不可能的。
  • @TJ “所以你告诉我有机会?”
  • @snookieordie 到目前为止,我还没有看到它在任何地方使用 jQuery UI 实现。真的,如果可能的话,已经有人这样做了。但仅仅因为到目前为止我还没有看到它,我不能断言它是不可能的。但我可以说,如果可能,那肯定会很困难;)

标签: javascript jquery jquery-ui drag-and-drop


【解决方案1】:

在没有真正的mousedown的情况下,实际上并没有太多的事情可以伪造拖动开始。虽然它可能会导致很多副作用,特别是如果您想与其他插件(例如 droppablesortable)结合使用,但这取决于您要查找的内容可能已经足够好了。

这是一个基本示例,您可以扩展它以满足您的需求:

window.onmousemove = function(e) {
  // for this example when you move over x = 200 an element is created
  // and dragging starts
  if (e.pageX > 200) {
   
    
    // you create the element
    var newEl = document.createElement('div');
    document.body.appendChild(newEl);
    newEl.classList.add('new');
    
    // set as draggable
    $(newEl).draggable();
    
    // get the instance
    var dragIns = $(newEl).draggable('instance');
    
    // trigger a mousedown with a which parameter to fake a left click
    $(newEl).trigger({type: 'mousedown', which: 1});
    
    // you set some variable and call some methods directly
    // on the instance to override normal behaviour
    dragIns._mouseStarted = true;
    
    // for mouse start you need the info of the mousemove event
    dragIns._mouseStart(e);
    dragIns.offset.click = {
      left: 8,
      top: 8
    };
	
    // run this only once
    window.onmousemove = null;
  }
}
.new {
  width: 20px;
  height: 20px;
  background-color: blue;
  position: absolute;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
 <link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">
<div>

</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多