将绝对元素重新定位到右侧

时间:2018-08-29 02:50:29

标签: javascript jquery jquery-animate

您好,我正在开发一个简单的应用程序,如果单击该应用程序,它将创建动画并向右移动。我的问题是它正朝相反的方向发展。我尝试使用css(),它有效,但是没有动画。我怎样才能做到这一点?还是有其他方法可以使它工作。

谢谢,希望你能理解我。

$('.circle').click(function(){
    $(this).animate({
      right: 200,
      top: 200,
      margin: 0
    },1000);
});
.circle{
  width: 100px;
  height: 100px;
  background-color: #222;
  border-radius: 100px;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circle"></div>

2 个答案:

答案 0 :(得分:2)

请勿使用边距使其居中,请使用calc,如下例所示:

$('.circle').click(function() {
  $(this).animate({
    right: 50,
    top: 25
  }, 1000);
});
.circle {
  width: 100px;
  height: 100px;
  background-color: #222;
  border-radius: 100px;
  position: absolute;
  top: calc(50vh - 50px);
  right: calc(50% - 50px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circle"></div>

答案 1 :(得分:0)

一种选择是从jQuery中删除margin: 0并将right属性更改为left。 (有关工作示例,请参见this笔。)

jQuery如下所示:

$('.circle').click(function() {
    $(this).animate({
      left: 200,
      top: 200
    }, 1000);
});
相关问题