用另一个元素开始拖动

时间:2011-12-26 08:38:55

标签: jquery draggable

是否可以使用其他元素开始拖动?

例如:http://jsbin.com/igohod/edit#preview

我想点击#ct时开始拖动#icon。值得注意的是,#icon并非来自DOM树中的#ct

HTML

  <div style="position:absolute; top:20px; left:10px;">
    <div id="icon">Icon</div>
  </div>

  <div style="position:absolute; top:20px; right:10px;">
    <div id="ct">start this drag when you drag the icon</div>
  </div>

JS

$(document).ready(function()
{
  // $('#icon').draggable();
  $('#ct').draggable();
});


更新:
可排序的新示例
http://jsbin.com/igohod/8/edit#preview

解决方案
http://jsbin.com/igohod/13/edit#preview

3 个答案:

答案 0 :(得分:11)

这样可行,但始终将其附加到列表的末尾:

 $(document).ready(function() {
   $('#icon').mousedown(function(e) {
     $('#ct').trigger(e);
   });
   $('#dropHere').sortable({ placeholder: 'ui-state-highlight' });
   $('#ct').draggable({ connectToSortable: '#dropHere' });

我还添加了CSS样式并删除了嵌套的div标签:

 #dropHere div{width:10; height:10; padding:10px; border:1px solid #000;}

http://jsbin.com/igohod/9/

答案 1 :(得分:3)

这是一个可能的解决方案:

$('#icon').draggable({drag: function(event, ui) {
    $("#ct").parent().css("top", 20 + parseInt($(this).css("top")));
    $("#ct").parent().css("left", 200 + parseInt($(this).css("left")));
}});

当您移动图标时,只需更新#ct的左侧和顶部值。

答案 2 :(得分:3)

使用帮助程序封装可拖动对象的另一种可能解决方案。这样您就不需要捕获任何鼠标事件或设置任意位置。 jQuery为你处理这个问题。

$(document).ready(function()
{

  $('#dropHere').sortable({ 
    placeholder: 'ui-state-highlight',
    receive: function(event, ui) {
      $(this).find('.drophandle').replaceWith(ui.helper);
      $(ui.helper).attr('style','');
    }
  });

  $('#icon').addClass('drophandle').draggable({
       connectToSortable: '#dropHere',
       cursorAt: { top: 15, left: 225 },
       helper: function() { return $('#ct')[0]; }
  });

});

http://jsbin.com/igohod/25

相关问题