2014-02-10 39 views
0

我想在用戶拖動鼠標時檢測到div碰撞。如何檢測我的情況下的div碰撞?

我有類似

<div id='drag-item'/> 
    <img src='drag' /> 
</div> 
<img id='img1' src='img1.png'/> 
<img id='img2' src='img21.png'/> 
<img id='img3' src='img3.png'/> 
<img id='img4' src='img4.png'/> 
<img id='img5' src='img5.png'/> 

    var objects = { 
        'img1': {'offset':330..other property...}, 
        'img2': {'offset':-450,other property...}, 
        'img3': {'offset' : 100,other property...} , 
        'img4': {'offset' : 430,other property...}, 
        'img5': {'offset' :-260,other property...} 
       } 

JS

$('#drag-item').draggable(
      drag: function(){ 
        var p = $('#drag-item').offset(); 

        for(var i in objects){ 
         var t = $('#' + i).position() 
         var hei = $('#' + i).height() + p.top; 

         if(p.top >= t.top && p.top <= hei){ 
          console.log('hit the object') 
         } 
        } 
      } 
    ) 

我想顯示「重災區對象」時,DIV被拖打形象之一,但我似乎無法到檢測碰撞。任何人都可以幫助我嗎?

回答

0

這裏是一些碰撞檢測可拖動對象:

$('#drag-item').draggable({ 
    drag: function (event, ui) { 
     var height = ui.helper.height(); 
     var divs = $('div.img').not($(this).children()); 

     var pos = ui.position; 

     divs.each(function (index, value) { 
      var t = $(this).position(); 
      var hei = $(this).height() 

      if (t.top <= pos.top + height) { // check for top collision 
       if (pos.left <= t.left + $(this).width()) { // check for side collision 
        console.log('hit the object'); 
       } 
      } 
     }); 
    } 
}); 

而一個Demo