限制可以移动div的区域

时间:2017-07-08 07:49:55

标签: javascript jquery html css jquery-ui

link反映了我的代码的实时预览。

HTML

<h1>Detect overlapping with JavaScript</h1>



<div id="area">
  <div id="box0"></div>
  <div id="box1">1</div>
  <div id="box2">2</div>
  <div id="box3">3</div>
  <div id="box4">4</div>
</div>

<div id="result"></div>


<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

的Javascript

var overlaps = (function() {
  function getPositions(elem) {
    var pos, width, height;
    pos = $(elem).position();
    width = $(elem).width();
    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]);
  };
})();

function m() {
  var area = $('#area')[0],
    box = $('#box0')[0],
    html;

  html = $(area).children().not(box).map(function(i) {

    if (overlaps(box, this)) {

      $("#box" + (i + 1)).removeClass('remTouch').addClass("touch");


    }
    return '<p>Red box + Box ' + (i + 1) + ' = ' + overlaps(box, this) + '</p>';


  }).get().join('');

  $('#result').html(html);


}

$('#box0').draggable({
  drag: function() {
    $(".touch").removeClass("touch").addClass('remTouch');
    m();
  }
});

我在此代码中有div,其中一个是可拖动的。它推动它碰撞的div。问题是我想在其中带来这样的功能:当它从上侧碰撞时它移动到下侧,同样地,当从左侧它将向右移动但不会越过其容器div的边界时。

0 个答案:

没有答案