jQuery UI draggable:绑定到mousemove事件中的对象

jQuery UI draggable: bind to object in mousemove event?

本文关键字:事件 对象 mousemove UI draggable 绑定 jQuery      更新时间:2023-09-26

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

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

提前谢谢。

实际上,在没有真正的鼠标向下的情况下,没有太多事情可以伪造拖动启动。不过,它可能会造成很多副作用,尤其是如果你想与其他插件组合,如可丢弃可以排序,但根据你想要的内容,它可能已经足够好了。

这里有一个基本的例子,你可能可以扩展它以满足你的需求:

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>