jQuery UI Droppable块由绝对div

时间:2013-01-08 16:19:35

标签: css jquery-ui

如何通过重叠的div阻止jquery ui droppable?

请参阅此示例:http://jsfiddle.net/JSFU4/3/。红色div覆盖可投放区域;但是,当拖动此区域顶部时,仍然会激活droppable。如何避免这种情况?

HTML

<div>
  <div class="drop">drop here</div>
</div>
<div>
  <div class="drag">drag me</div>
</div>
<div class="overlay">i want to block the droppable</div>

CSS

.drag {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background-color: lightblue;
  z-index: 1;  
}
.drop {
  display: inline-block;
  border: 1px dotted black;
  width: 200px;
  height: 200px;
}
.drop-hover {
  background-color: grey;
}
.overlay {
  position: absolute;
  width: 300px;
  height: 100px;
  top: 50px;
  background-color: red;
  border: 1px solid black;
}

JS

$(function () {
  $('.drag').draggable();
  $('.drop').droppable({
    tolerance: 'pointer',
    hoverClass: 'drop-hover'    
  });
});

1 个答案:

答案 0 :(得分:0)

我认为没有什么可以实现这一目标。您需要进行某种碰撞检测,然后相应地进行逻辑运算。我为你做过POC。

DEMO

var drag = $('.drag');
var overlay = $('.overlay');

$(function () {
  $('.drag').draggable();
  $('.drop').droppable({
    tolerance: 'pointer',
    hoverClass: 'drop-hover'
  });
});


var int = self.setInterval(function () {
  if (overlaps(drag, overlay)) {
    $('.drop').css('visibility', 'hidden');
  } else {
     $('.drop').css('visibility', 'visible');
  }
}, 100);


var overlaps = (function () {
  function getPositions(elem) {
    var pos, width, height;
    pos = $(elem).position();
    width = $(elem).width() / 2;
    height = $(elem).height();
    return [[pos.left, pos.left + width], [pos.top, pos.top + height]];
  }

  function comparePositions(p1, p2) {
    var r1, r2;
    r1 = p1[0] < p2[0] ? p1 : p2;
    r2 = p1[0] < p2[0] ? p2 : p1;
    return r1[1] > r2[0] || r1[0] === r2[0];
  }

  return function (a, b) {
    var pos1 = getPositions(a),
      pos2 = getPositions(b);
    return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
  };
})();

上面的代码检测到两个DIV之间的冲突并返回truefalse