编程语言
首页 > 编程语言> > javascript-使用jquery-ui在droppable内将可拖动元素居中

javascript-使用jquery-ui在droppable内将可拖动元素居中

作者:互联网

以下是到目前为止我可以实现的示例…

$(document).ready(function() {
  $(".item").draggable({
    revert: 'invalid',
    snapMode: 'inner',
    scroll: false,
    stack: false,
    drag: function(event, ui) {
      $(".droparea").removeClass("highlight");
    }
  });
  $(".droparea").droppable({
    tolerance: 'intersect',
    drop: function(event, ui) {
      var drop_el = $(this).offset();
      var drag_el = ui.draggable.offset();
      var left_end = (drop_el.left + ($(this).width() / 2)) - (drag_el.left + (ui.draggable.width() / 2));
      var top_end = (drop_el.top + ($(this).height() / 2)) - (drag_el.top + (ui.draggable.height() / 2));
      $(this).addClass("highlight").find("p");
      ui.draggable.animate({
        top: '+=' + top_end,
        left: '+=' + left_end
      });
    }
  });
});
.item {
  position: relative;
  margin: 0 auto;
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin-top: 50%;
  top: -50px
}
.droparea {
  width: 150px;
  height: 150px;
  float: left;
  margin: 10px;
  border: 1px solid #000;
}
.highlight {
  border: 1px solid blue
}
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>

<div class="droparea">
  <div class="item"></div>
</div>

<div class="droparea">

</div>

有时,它拒绝将.item div居中… .item div必须拖到.droparea元素的内部,否则,在释放item元素后,就不会将.item元素居中.
只是想知道是否还有其他更优雅的方法来使可拖动div居中到最接近的droppable元素.

解决方法:

您可以使用jQuery UI的内置position()实用程序方法将放置的项居中,如下所示:

$(document).ready(function() {
  $(".item").draggable({
    scroll: false,
    revert: 'invalid',
    stack: false,
    cursor: "pointer",
    drag: function(event, ui) {
      $(".droparea").removeClass("highlight");
    }
  });
  $(".droparea").droppable({
    accept: ".item",
    drop: function(event, ui) {
      var $this = $(this);
      $(".highlight").removeClass("highlight");
      $this.addClass("highlight");
      ui.draggable.position({
        my: "center",
        at: "center",
        of: $this,
        using: function(pos) {
          $(this).animate(pos, "slow", "linear");
        }
      });
    }
  });
});
.item {
  position: relative;
  margin: 0 auto;
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
.droparea {
  width: 150px;
  height: 150px;
  float: left;
  margin: 2px;
  border: 1px solid #000;
  outline: 1px solid transparent
}
.highlight {
  border: 1px solid blue
}
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>

<div class="droparea">
  <div class="item"></div>
</div>


<div class="droparea"></div>
<div class="droparea"></div>

标签:jquery-ui-draggable,jquery-ui,jquery-ui-droppable,javascript,jquery
来源: https://codeday.me/bug/20191029/1956761.html