【问题标题】:add animation to offset将动画添加到偏移量
【发布时间】:2018-07-25 10:35:26
【问题描述】:

我正在开发一个将元素移动到特定位置的简单应用程序。我成功移动了元素,但我想在移动时添加动画。我尝试使用动画而不是偏移,但不起作用。

希望你能帮助我。

谢谢。

$('button').click(function(){
   var offset = $('.target').offset();
   var object = $('.object');
  
    object.offset({top: offset.top, left: offset.left});
});
.container{
  width: 120px;
  height: 150px;
  text-align: center;
}

.target{
  margin: 0 auto;
  width: 100px;
  height: 100px;
  background-color: #DDD;
  margin-bottom: 100px;
}

.object{
  margin: 0 auto;
  width: 50px;
  height: 50px;
  background-color: brown;
}
button{
  margin-top:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="target"></div>
  <div class="object"></div>
  <button>MOVE</button>
</div>

【问题讨论】:

    标签: jquery jquery-animate


    【解决方案1】:

    您需要将 $('.object') 的位置设置为绝对位置。 您可以在 jquery 中设置它,而不是像这样使用动画:

    $('button').click(function(){
       var offset = $('.target').offset();
      $('.object').css("position","absolute")
      .animate({
      "top":offset.top,
      "left":offset.left
      })
    });
    

    或使用 css 设置(在这种情况下,您必须设置对象的初始顶部和左侧)。

    工作示例:jsFiddle

    【讨论】:

    • 谢谢,有没有办法让方向变直。
    • @Mark 如果您想同时更改垂直和水平位置,请不要。如果这不是你想要的,那么你需要更好地解释,因为这正是你到目前为止所问的。
    • 直是什么意思?您可以设置 $('.object') 和 $('.container') 的初始 css,这样它们都将具有相同的“left”属性值。比它看起来像直线上升。
    【解决方案2】:

    要为div.object 设置动画,需要将其位置设置为absolute。并根据您对div.objectbutton 的要求在以下代码sn-ps 中检查更新的CSS。

    代码 sn-ps:

    $('button').click(function() {
      var offset = $('.target').offset();
      var object = $('.object');
      object.animate({
        top: offset.top,
        left: offset.left
      });
    });
    .container {
      width: 120px;
      height: 150px;
      text-align: center;
    }
    
    .target {
      margin: 0 auto;
      width: 100px;
      height: 100px;
      background-color: #DDD;
      margin-bottom: 100px;
    }
    
    .object {
      width: 50px;
      height: 50px;
      background-color: brown;
      position: absolute;
      left: 43px;
    }
    
    button {
      top: 70px;
      position: relative;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
      <div class="target"></div>
      <div class="object"></div>
      <button>MOVE</button>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2011-07-25
      相关资源
      最近更新 更多