【问题标题】:Improper position during animation动画期间位置不正确
【发布时间】:2016-02-11 05:34:10
【问题描述】:

我有两个使用 Jquery 拖放的可交换 div。

当我尝试使用拖动来交换 div 时,动画期间 div 的位置不正确。 div 的交换正常进行,但问题出在动画期间。

HTML

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" id="toz">Open Modal</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <div class='droppable'>
          <div class="draggable">Draggable 1</div>
        </div>

        <div class='droppable'>
          <div class="draggable">Draggable 2</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

JavaScript

$(document).ready(function() {
  window.startPos = window.endPos = {};

    makeDraggable();

  $('.droppable').droppable({
    hoverClass: 'hoverClass',
    drop: function(event, ui) {
      var $from = $(ui.draggable),
        $fromParent = $from.parent(),
        $to = $(this).children(),
        $toParent = $(this);

      window.endPos = $to.offset();

      swap($from, $from.offset(), window.endPos, 200);
      swap($to, window.endPos, window.startPos, 1000, function() {
        $toParent.html($from.css({
          position: 'relative',
          left: '',
          top: '',
          'z-index': ''
        }));
        $fromParent.html($to.css({
          position: 'relative',
          left: '',
          top: '',
          'z-index': ''
        }));
        makeDraggable();
      });
    }
  });

  function makeDraggable() {
    $('.draggable').draggable({
      zIndex: 99999,
      revert: 'invalid',
      start: function(event, ui) {
        window.startPos = $(this).offset();
      }
    });
  }

  function swap($el, fromPos, toPos, duration, callback) {
    $el.css('position', 'absolute')
      .css(fromPos)
      .animate(toPos, duration, function() {
        if (callback) callback();
      });
  }

});

Fiddle demo of problem

【问题讨论】:

    标签: javascript jquery html animation jquery-animate


    【解决方案1】:

    只需将绝对值更改为固定值即可。 Fiddle

    function swap($el, fromPos, toPos, duration, callback) {
        $el.css('position', 'fixed')
          .css(fromPos)
          .animate(toPos, duration, function() {
            if (callback) callback();
          });
      }
    

    【讨论】:

    • 有什么区别?
    • 我将绝对位置改为固定位置
    • 我的意思是为什么会这样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多