【问题标题】:Start drag with another element用另一个元素开始拖动
【发布时间】:2012-01-27 21:09:18
【问题描述】:

是否可以用另一个元素开始拖动?

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

当我点击#icon 时,我想开始拖动#ct。值得注意的是,#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

【问题讨论】:

    标签: jquery draggable


    【解决方案1】:

    这可行,但总是将其附加到列表的末尾:

     $(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/

    【讨论】:

    • 我认为新 div 只出现在可排序 div 底部的原因是鼠标坐标和新 div 永远不会在可排序 div 中...
    • 我是对的。如果将 div 移动到光标处,则 sortable 可以正常工作。 jsbin.com/igohod/11
    • 完美!我只是将 cursorAt: { top: 15, left: 225 } 添加到可拖动对象中,效果非常好!
    【解决方案2】:

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

    $('#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 的 left 和 top 值。

    【讨论】:

    • 我不想改变图标的​​位置:/ ...感谢您的快速回答。
    • 对不起,我的例子不太好。我想将 #ct 放入可排序的列表中。这就是我尝试用其他元素“启动”拖动的原因。这是一个例子:jsbin.com/igohod/6/edit#javascript,html
    • 有什么理由不能将这两个元素包装在一个 div 中并使用它?
    • @Tank 图标必须是静态的。
    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多