add animation to offset

2019-08-26 00:29发布

问题:

I'm working on a simple app that move an element to a specific position. I succeed to move the element, but I want to add animation, while it is being move. I tried to use animate instead of offset but doesn't work.

hope you help me.

Thanks.

$('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>

回答1:

you need to set the position of $('.object') to absolute. you can set it either in jquery and than use animate like so:

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

or set it with css (in this case you will have to set the initial top and left of the object).

working examle: jsFiddle



回答2:

To animate the div.object, need to set its position as absolute. And also check the updated CSS in following code snippets as per your requirement for div.object and button.

Code snippets:

$('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>