2009-07-02 122 views
0

我想检测,看是否元素被拖出容器。jQuery的拖放问题

例如:

<div id="container"> 
    <img src="xxx.png" /> 
</div> 

,如果我拖动img元素出来的div。我将删除 img元素,但我不知道如何检测img是否超出div。

我是使用jQuery拖放库。

回答

4

有一个简单的方法来做到这一点。

  1. 设置孩子拖动
  2. 设置家长可放开
  3. 设置一个标志,如果拖曳停止真正删除元素
  4. 取消设置该标志在降功能父母
  5. 孩子拖出来父母==子女未落入父母

因此,当您在父母身边移动父母时,没有任何事情发生(removeMe标志未设置)然后它回到原来的位置。

如果拖动孩子家长外的removeMe标志不是取消设置和牵引止挡的方法去除的孩子。

的JavaScript

$("#draggable").draggable({ 
    start: function(event, ui) { 
    // flag to indicate that we want to remove element on drag stop 
    ui.helper.removeMe = true; 
    }, 
    stop: function(event, ui) { 
    // remove draggable if flag is still true 
    // which means it wasn't unset on drop into parent 
    // so dragging stopped outside of parent 
    if (ui.helper.removeMe) { 
     ui.helper.remove(); 
    } 
    }, 
    // move back if dropped into a droppable 
    revert: 'valid' 
}); 

$("#droppable").droppable({ 
    drop: function(event, ui) { 
    // unset removeMe flag as child is still inside parent 
    ui.helper.removeMe = false; 
    } 
}); 

HTML

<div id="droppable"> 
    <p id="draggable">Drag me!</p> 
</div> 
0

你需要通过添加类似的功能添加一个div您的容器

<div id="droppableDiv"> 
    <div id="container"> 
     <img src="xxx.png" /> 
    </div> 
</div> 

外面,然后使它可放开:

$("#droppableDiv").droppable ({ 
    drop: function() { alert('dropped'); } 
}); 

,而不是警报(“下降”);部分你可以添加一些代码从容器div中移除img元素。

here是,做一些其他的事情,但利用可放开和可拖动对象的例子,也许它可以帮助您了解它是如何工作!

希望这有助于

-Fortes

1

感谢你提供了解决方案。

我已经找到了其他的解决方案,而不需要对这一问题的外层div。

我用“距离”选项来检测鼠标多久移动,然后用 “停止”选项去掉元素。

$(".droppable").droppable({ 
    drop: function(event, ui) { 
     var obj = $(ui.draggable).clone(); 
     obj.draggable({ 
        distance: 100,//used to measure how far my mouse moved. 
        helper: 'clone', 
        opacity : 0.35, 
         stop: function(event, ui) { 
          $(this).remove();//remove this element. 
         } 

         } 

     );//obj.draggable 
    }//drop 
})