0

So I have a draggable object- How can I test if its stop position is in a certain range (over a div)

best i can do is find its exact position. Thanks.

Fiddle http://jsfiddle.net/f5n66/

 $( init );

function init() {
  $('.draggable').draggable({
  opacity:0.7, helper:"clone",
  stop: function(event, ui) {
    if(ui.position === $('#resultArea').position()){
        console.log(ui.position);
        }
}
  });

}

4

1 回答 1

1

您需要检查 drop 是否在 dropzone div 的维度内。

function init() {
  $('.draggable').draggable({
  opacity:0.7, helper:"clone",

  stop: function(event, ui) {
      var coords = $('#resultArea').position();
      coords.bottom = coords.top + $('#resultArea').height();
      coords.bottomRight = coords.left + $('#resultArea').width();
        if(ui.position.top >= coords.top && ui.position.top <= coords.bottom && ui.position.left >= coords.left && ui.position.left <= coords.bottomRight){
            console.info("inside");
        }else{
             console.info("outside");   
        }
    }
      });
}

现场演示

更新: 将计算放在单独的函数中以使其可重用

function inDropZone(drag, drop){
    var coords = drop.position();
    coords.bottom = coords.top + drop.height();
    coords.bottomRight = coords.left + drop.width();
    if(drag.position.top >= coords.top && drag.position.top <= coords.bottom && drag.position.left >= coords.left && drag.position.left <= coords.bottomRight){
        return true;
    }else{
         return false;
    }
}
于 2014-02-14T15:17:29.273 回答