2016-05-31 29 views

回答

0

对不起,这不是越早回答。我相信你必须手动检查元素上,下,左,右边缘的位置,所以这里是我做过什么:

//Call this function from within your .on('dragmove') method. 
//It should replace your translations. 

function noOverlap(event, overlapElements){ 

    //just for flagging when the target would overlap another element 
    var overlap = false; 
    var targetDims = event.target.getBoundingClientRect(); 

    for(i = 0; i < overlapElements.length; i++){ 
     var overlapElementDims = 
     overlapElements[i].getBoundingClientRect(); 

     //make sure the element doesn't look at itself.. 
     if(overlapElements[i] != event.target){ 
      //checks if the target "doesn't" overlap 
      if(((targetDims.right + dx) < (overlapElementDims.left + 1)) 
      ||((targetDims.left + 1 + dx) > (overlapElementDims.right)) 
      ||((targetDims.top + 1 + dy) > (overlapElementDims.bottom)) 
      ||((targetDims.bottom + dy) < (overlapElementDims.top + 1))}{ 

      //Basically, the target element doesn't overlap the current 
      //element in the HTMLCollection, do nothing and go to the 
      //next iterate 
      } 
      else{ 
       //This is if the target element would overlap the current element 

       //set overlap to true and break out of the for loop to conserve time. 

       overlap = true; 
       break; 
      } 
     } 
    }; 

    if(overlap === false){ 

     //if there's no overlap, do your normal stuff, like: 
     event.target.x += dx; 
     event.target.y += dy; 

     event.target.style.webkitTransform = 
      event.target.style.transform = 
       'translate(' + event.target.x + 'px, ' + event.target.y + 'px)'; 

     //then reset dx and dy 
     dy = 0; 
     dx = 0; 
    } 
    else{ 
     if(event.interaction.pointers[event.interaction.pointers.length - 1].type 
     === "pointerup"){ 

      //check if the target "is" in the restriction zone 
      var restriction = 
      interact(event.target).options.drag.restrict.restriction; 
      var restrictionDims = restriction.getBoundingClientRect(); 

      if((targetDims.right > restrictionDims.right) || 
      (targetDims.left < restrictionDims.left) || 
      (targetDims.bottom > restrictionDims.bottom) || 
      (targetDims.top < restrictionDims.top)){ 
       event.target.style.webkitTransform = 
       event.target.style.transform = 
        'translate(0px, 0px)'; 

       //then reset dx and dy 
       dy = 0; 
       dx = 0; 

       //then reset x and y 
       event.target.x = 0; 
       event.target.y = 0; 
      } 
     }  
    } 
} 
+0

另外,如果有人结束了读这篇文章,请让我知道什么我所能做的就是提高效率。 – KirklandBrown373

+0

我已经停止通过更新拖动元素的位置拖动,但任何想法如何我可以停止在这种情况下移动鼠标指针? – not2savvy

+0

停止移动鼠标指针是与js交互的完全不同的主题。我会看看这样的:http://www.smartjava.org/content/html5-use-pointer-lock-api-restrict-mouse-movement-element – KirklandBrown373