如何在拖放时使拖动的元素位于可放置区域的中心

时间:2017-01-23 09:45:54

标签: jquery html jquery-ui

我有一个div

<div class="row">
  <div class="col-xs-4 drop12">
    // content goes
  </div>
</div>

<div class="row">
  <p class="col-xs-4 drag12">
    // content goes
  </p>
</div>

我的问题是如何使用jquery-ui将可拖放区域中的拖放元素放在droppable div的中心

$('.drag12').draggable();
$('.drop12').droppable();

可以查看小提琴https://jsfiddle.net/fefcn9nm/1/

1 个答案:

答案 0 :(得分:0)

https://jsfiddle.net/fefcn9nm/6/

$(document).ready(function(){
  var offsetCenter;

  $('.drop12').droppable();
  $('.drop12').on('drop', function( event, ui ) {
     var $divDrop = $(this);
     offsetCenter = {
       top: $divDrop.offset().top + $divDrop.height()/2,
       left: $divDrop.offset().left + $divDrop.width()/2
     }

     var diffLeft = offsetCenter.left - event.pageX,
            diffTop = offsetCenter.top - event.pageY;

      $(ui.draggable).css({
         left:  parseInt($(ui.draggable).css('left')) + diffLeft,
         top:  parseInt($(ui.draggable).css('top')) + diffTop
      })
  });

  $('.drag12').draggable();
})